poj - 3669 Meteor Shower -- BFS
Description
Bessie hears that an extraordinary meteor shower is coming; reports say that these meteors will crash into earth and destroy anything they hit. Anxious for her safety, she vows to find her way to a safe location (one that is never destroyed by a meteor) . She is currently grazing at the origin in the coordinate plane and wants to move to a new, safer location while avoiding being destroyed by meteors along her way.
The reports say that M meteors (1 ≤ M ≤ 50,000) will strike, with meteor i will striking point (Xi, Yi) (0 ≤ Xi ≤ 300; 0 ≤ Yi ≤ 300) at time Ti (0 ≤ Ti ≤ 1,000). Each meteor destroys the point that it strikes and also the four rectilinearly adjacent lattice points.
Bessie leaves the origin at time 0 and can travel in the first quadrant and parallel to the axes at the rate of one distance unit per second to any of the (often 4) adjacent rectilinear points that are not yet destroyed by a meteor. She cannot be located on a point at any time greater than or equal to the time it is destroyed).
Determine the minimum time it takes Bessie to get to a safe place.
Input
* Line 1: A single integer: M
* Lines 2..M+1: Line i+1 contains three space-separated integers: Xi, Yi, and Ti
Output
* Line 1: The minimum time it takes Bessie to get to a safe place or -1 if it is impossible.
Sample Input
4 0 0 2 2 1 2 1 1 2 0 3 5
Sample Output
5
题意:
首先呢讲一下题目的大意,Bessie从原点出发,然后有N个流星会在某个时刻落下,它们会破坏
砸到的这个方格还会破坏四边相邻的方块,Bessie不能经过被破坏的方块,问Bessie到一个安全的地方(不会被任何流星砸到)
至少需要多少时间(移动一格的时间为1),如果不可能,则输出-1
思路:
代码:
#include <cstdio> #include <algorithm> #include <vector> #include <iostream> #include <cstring> #include <queue> #define maxn 400 #define mem(a,b) memset(a,b,sizeof(a)) #define Pair pair<int,int> using namespace std; int map1[maxn][maxn];//预处理 int map2[maxn][maxn];//记录步数 int d[4][2] = {1,0,-1,0,0,1,0,-1}; void init(int m) { int x,y,time; mem(map1,-1); mem(map2,0); for(int i = 0;i < m;i++){ scanf("%d%d%d",&x,&y,&time); if(map1[x][y] == -1) map1[x][y] = time; else if(map1[x][y] > time) map1[x][y] = time; for(int j = 0;j < 4;j++){ int nx = x+d[j][0]; int ny = y+d[j][1]; if(nx<0 || ny<0)continue; if(map1[nx][ny]==-1)map1[nx][ny] = time; else if(map1[nx][ny] > time) map1[nx][ny] = time; } } } int bfs() { if(map1[0][0] == 0)return -1; if(map1[0][0] == -1)return 0; queue<Pair> que; while(!que.empty())que.pop(); que.push(Pair(0,0)); while(!que.empty()){ Pair p = que.front(); que.pop(); for(int j = 0;j < 4;j++){ int nx = p.first+d[j][0]; int ny = p.second+d[j][1]; if(nx<0 || ny<0)continue; ///不优化会超时 不能再经过之前搜过的点 if(map2[nx][ny]!=0)continue; if(map1[nx][ny] == -1) return map2[p.first][p.second]+1; map2[nx][ny] = map2[p.first][p.second]+1; if(map2[nx][ny] < map1[nx][ny]) que.push(Pair(nx,ny)); } } return -1; } int main() { freopen("in.txt","r",stdin); int m;scanf("%d",&m); init(m); printf("%d\n",bfs()); return 0; }
重点。。。。要注意优化,BFS不可经过过去经过的点 Orz
if(map2[nx][ny]!=0)continue; //。。。一直TLE。。。。弱的yipi。。。 //优化后就ok