HDU 1072 优先队列的使用
思路很简单,一开始没有用优先队列,WA了几次后来改了,想一想走迷宫停顿时应该用优先队列。if(u.btime==1) continue;此句不能省略当时间为1时,这一步无法出去,只有重新来过
View Code
1 #include<cstdio> 2 #include<cstdlib> 3 #include<iostream> 4 #include<cstring> 5 #include<queue> 6 7 using namespace std; 8 int N,M,map[10][10]; 9 int dx[] = {0,0,-1,1}; 10 int dy[] = {1,-1,0,0}; 11 typedef struct 12 { 13 int x,y; 14 int step; 15 int btime; 16 }Point; 17 Point P[100]; 18 19 int True(Point P) 20 { 21 if(P.x<N&&P.x>=0&&P.y>=0&&P.y<M) 22 return 1; 23 return 0; 24 } 25 26 priority_queue<Point> q; 27 bool operator<(Point a, Point b) 28 { 29 return a.step > b.step; 30 } 31 32 int main() 33 { 34 int i,j,ncases; 35 int sx,sy,tx,ty,ok; 36 Point start,target; 37 38 scanf("%d",&ncases); 39 while( ncases-- ) 40 { 41 scanf("%d%d",&N,&M); 42 for(i=0; i<N; i++) 43 for(j=0; j<M; j++) 44 { 45 scanf("%d",&map[i][j]); 46 } 47 for(i=0; i<N; i++) 48 for(j=0; j<M; j++) 49 { 50 if(map[i][j] == 2) 51 { 52 start.x = i; 53 start.y = j; 54 } 55 if(map[i][j] == 3) 56 { 57 target.x = i; 58 target.y = j; 59 } 60 } 61 start.step = 0; 62 ok = 0; 63 start.btime = 6; 64 q.push(start); 65 while( !q.empty() ) 66 { 67 Point u = q.top(); 68 q.pop(); 69 if(u.x==target.x && u.y==target.y) 70 { 71 ok = 1; 72 printf("%d\n",u.step); 73 break; 74 } 75 if(u.btime == 1) continue; 76 for(i=0; i<4; i++) 77 { 78 Point v; 79 v.x = u.x + dx[i]; 80 v.y = u.y + dy[i]; 81 if(True(v) && map[v.x][v.y]) 82 { 83 v.btime = u.btime-1; 84 v.step = u.step + 1; 85 if(map[v.x][v.y]==4) 86 { 87 v.btime = 6; 88 map[v.x][v.y] = 0; 89 } 90 q.push(v); 91 } 92 } 93 } 94 while( !q.empty()) 95 q.pop(); 96 if(!ok) 97 printf("-1\n"); 98 } 99 system("pause"); 100 return 0; 101 } 102