程设模拟考 G:拯救行动
题目见此:http://cxsjsx.openjudge.cn/2013weekend/5G/
解题思路:
- 广搜
- 守卫要走两步,需要特殊处理。我的处理方法是遇到守卫把,就在把这个点重新加入队列,下一次再取出,这样就保证了队列的优先性。也可以直接用优先队列。
贴代码:
1 #include <iostream> 2 #include <queue> 3 #include <string.h> 4 using namespace std; 5 struct Point 6 { 7 int x, y, time; 8 bool stay; 9 Point():stay(0){} 10 }; 11 Point p, ne; 12 int r, c, dx[]={1, 0, -1, 0}, dy[]={0, 1, 0, -1}; 13 char a[210][210]; 14 queue<Point> q; 15 16 void bfs() 17 { 18 q.push(p); 19 while(!q.empty()) 20 { 21 p = q.front(); q.pop(); 22 if(p.stay == 1) 23 { 24 p.time++; 25 p.stay = 0; 26 q.push(p); 27 continue; 28 } 29 for(int k=0 ; k<4 ; k++) 30 { 31 ne.x = p.x+dx[k], ne.y = p.y+dy[k], ne.time = p.time+1; 32 ne.stay = 0; 33 switch(a[ne.x][ne.y]) 34 { 35 case '@':q.push(ne); a[ne.x][ne.y]=0;break; 36 case 'a':return; 37 case 'x': 38 ne.stay = 1; q.push(ne); a[ne.x][ne.y]=0;break; 39 } 40 } 41 } 42 } 43 44 int main() 45 { 46 int s; cin >> s; 47 while(s--) 48 { 49 while(!q.empty()) q.pop(); 50 cin >> r >> c; 51 memset(a, 0, sizeof(a)); 52 for(int i=1 ; i<=r ; i++) 53 for(int j=1 ; j<=c ; j++) 54 { 55 cin >> a[i][j]; 56 if(a[i][j] == 'r') 57 { 58 p.x = i, p.y = j, p.time = 0; 59 a[i][j] == 0; 60 } 61 else if(a[i][j] == '#') 62 a[i][j] = 0; 63 } 64 bfs(); 65 if(a[ne.x][ne.y] == 'a') 66 cout << ne.time << endl; 67 else 68 cout << "Impossible" << endl; 69 } 70 }
这题其实挺简单的……但上机时没有做出来。WHY?因为没有加第49行的刷新队列……上机完仔细看了遍代码,然后加了那一行就直接AC了。当时好可惜啊
浙公网安备 33010602011771号