Http://acm.hdu.edu.cn/showproblem.php? PID = 1, 1242
The first idea after reading the question is to take the position of each friend as the starting point BFS out step and take the minimum value. After submission, WA, modify and submit TLE.
This is a multi-to-one search, which in turn is one-to-many. The step required for the first searched friend is the minimum value. After the change, submit again and still wa...
After reading other people's problem-solving reports, the priority queue is basically used, but the content of the priority queue is not as complicated as imagined. In struct
Added the custom priority operator <a little changed to AC. Suddenly found that the priority queue is so easy to use...
C ++ submit exe. Time 31 MS exe. Memory 288 K
G ++ submit exe. Time 187 MS exe. Memory 356 Kb
/* If the custom operator is>, the compilation will fail (G ++ compiler)
Because the standard library uses the <operator of the element type by default to determine the priority relationship between them.
The <operator and> operator of the custom type is not directly related, so it cannot be compiled. */
# Include <iostream>
# Include <cstdio>
# Include <queue>
Using namespace STD;
Char map [201] [201];
Int Tur [4] [2] = {0, 1, 0,-1,-1, 0, 1, 0 };
Int n, m;
Struct node {
Int X, Y;
Int step;
Friend bool operator <(node T1, node T2) {// custom priority
Return t1.step> t2.step;
}
} Start;
Void BFS (node begin ){
Priority_queue <node> q; // priority queue
Q. Push (BEGIN );
While (! Q. Empty ()){
Node P = Q. Top ();
Q. Pop ();
For (INT I = 0; I <4; I ++ ){
Node temp = P;
Temp. x + = Tur [I] [0];
Temp. Y + = Tur [I] [1];
If (temp. x> = 0 & temp. x <n & temp. y> = 0 & temp. Y <M & map [temp. x] [temp. y]! = '#'){
Temp. Step = P. Step + 1;
If (Map [temp. x] [temp. Y] = 'R '){
Printf ("% d \ n", temp. Step );
Return;
}
If (Map [temp. x] [temp. Y] = 'X '){
Temp. Step ++;
// Map [temp. x] [temp. Y] = '.';
}
Map [temp. x] [temp. Y] = '#';
Q. Push (temp );
}
}
}
Printf ("Poor Angel has to stay in the prison all his life. \ n ");
Return;
}
Int main (){
While (~ Scanf ("% d", & N, & M )){
For (INT I = 0; I <n; I ++)
For (Int J = 0; j <m; j ++ ){
Cin> map [I] [J];
If (Map [I] [J] = 'A '){
Start. x = I;
Start. Y = J;
Start. Step = 0;
}
}
BFS (start );
}
Return 0;
}