标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 13911 Accepted Submission(s): 4370 Special Judge
1 #include<queue> 2 #include<algorithm> 3 #include<stdio.h> 4 #include<string.h> 5 #include<ctype.h> 6 const int M = 100 + 10 , inf = 0x3f3f3f3f ; 7 int n , m; 8 char map[M][M] ; 9 bool vis[M][M] ; 10 int move[][2] = {{1,0} , {-1,0} , {0,1} , {0,-1}} ; 11 struct node 12 { 13 int x , y , time ; 14 int pet ; 15 int nxt ; 16 }e[90000 + 10]; 17 int l , r ; 18 int cas ,k ; 19 20 bool cmp (node a , node b) 21 { 22 return a.time < b.time ; 23 } 24 void bfs () 25 { 26 node ans , tmp ; 27 l = 0 , r = 1 ; 28 k = 0 ; 29 for (int i = 0 ; i < n ; i ++) for (int j = 0 ; j < m ; j ++) vis[i][j] = 0; 30 e[l].x = 0 , e[l].y = 0 , e[l].time = 0 , e[l].nxt = - 1 , e[l].pet = 0 ; 31 while (l != r) { 32 std::sort (e + l , e + r , cmp ) ; 33 //printf ("(%d,%d)\n" , e[l].x , e[l].y ) ; 34 ans = e[l] ; 35 if (e[l].x == n - 1 && e[l].y == m - 1) {k = 1 ; return ;} 36 // printf ("S====(%d,%d)\n" , ans.x , ans.y ) ; 37 for (int i = 0 ; i < 4 ; i ++) { 38 tmp.x = ans.x + move[i][0] , tmp.y = ans.y + move[i][1] ; tmp.pet = 0 ; 39 if (tmp.x < 0 || tmp.y < 0 || tmp.x >= n || tmp.y >= m) continue ; 40 if (map[tmp.x][tmp.y] == ‘X‘ ) continue ; 41 if (vis[tmp.x][tmp.y]) continue ; 42 if ( isdigit ( map[tmp.x][tmp.y] ) ) {tmp.time = ans.time + 1 + map[tmp.x][tmp.y] - ‘0‘ ; tmp.pet = map[tmp.x][tmp.y] - ‘0‘ ;} 43 else tmp.time = ans.time + 1 ; 44 tmp.nxt = l ; 45 vis[tmp.x][tmp.y] = 1 ; 46 // printf ("(%d,%d)\n" , tmp.x , tmp.y ) ; 47 e[r ++] = tmp ; 48 } 49 l ++ ; 50 } 51 } 52 53 void solve (int k) 54 { 55 if (k == -1) return ; 56 solve (e[k].nxt) ; 57 int t = e[k].nxt ; 58 if ( t != -1 ) { 59 printf ("%ds:(%d,%d)->(%d,%d)\n" , cas ++ , e[t].x , e[t].y , e[k].x , e[k].y ) ; 60 for (int i = 0 ; i < e[k].pet ; i ++) printf ("%ds:FIGHT AT (%d,%d)\n" , cas ++ , e[k].x , e[k].y) ; 61 } 62 } 63 64 int main () 65 { 66 // freopen ("a.txt" , "r" , stdin ) ; 67 while (~ scanf ("%d%d" , &n , &m)) { 68 for (int i = 0 ; i < n ; i ++) scanf ("%s" , map[i]) ; 69 bfs () ; 70 if (k) { 71 printf ("It takes %d seconds to reach the target position, let me show you the way.\n" , e[l].time ) ; 72 cas = 1 ; 73 solve (l) ; 74 puts ("FINISH") ; 75 } 76 else { 77 puts ("God please help our poor hero.") ; 78 puts ("FINISH") ; 79 } 80 } 81 return 0 ; 82 }
这种不需要走回头路的,而且走的过程中会出现罚时的题目,就用优先队列吧.
发现输出路径的用模拟来写很方便.
hdu1026.Ignatius and the Princess I(bfs + 优先队列)
标签:
原文地址:http://www.cnblogs.com/get-an-AC-everyday/p/4468648.html