3432: Meteor Shower
描述
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.
输入
* Line 1: A single integer: M
* Lines 2..M+1: Line i+1 contains three space-separated integers: Xi, Yi, and Ti
输出
* Line 1: The minimum time it takes Bessie to get to a safe place or -1 if it is impossible.
样例输入
4
0 0 2
2 1 2
1 1 2
0 3 5
样例输出
5
BFS,注意要更新流星的下落时间,(可能同一地点有多次下落),然后流星下落点的上下左右四个方向也将受影响。
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
int ma[310][310];
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
int mark[310][310];
struct node
{
int x,y,step;
}temp,a;
bool operator < (const node &a,const node &b)
{
return a.step>b.step;
}
void bfs()
{
int i;
memset(mark,0,sizeof(mark));
priority_queue<node>q;
a.x=0;
a.y=0;
a.step=0;
q.push(a);
mark[0][0]=1;
while(!q.empty())
{
a=q.top();
q.pop();
if(ma[a.x][a.y]==-1)
{
printf("%d\n",a.step);
return;
}
for(i=0;i<4;i++)
{
temp.x=a.x+dir[i][0];
temp.y=a.y+dir[i][1];
temp.step=a.step+1;
if(temp.x>=0&&temp.y>=0&&(ma[temp.x][temp.y]==-1||ma[temp.x][temp.y]>temp.step))
{
if(!mark[temp.x][temp.y])
q.push(temp);
mark[temp.x][temp.y]=1;
}
}
}
printf("-1\n");
}
int main()
{
int n,x,y,t,i,j;
while(scanf("%d",&n)!=EOF)
{
memset(ma,-1,sizeof(ma));
for(i=0;i<n;i++)
{
scanf("%d%d%d",&x,&y,&t);
if(ma[x][y]==-1)
ma[x][y]=t;
else
ma[x][y]=min(ma[x][y],t);//撞击时间更新
for(j=0;j<4;j++)//四个方向均受影响
{
int nx=x+dir[j][0];
int ny=y+dir[j][1];
if(nx>=0&&ny>=0)
{
if(ma[nx][ny]==-1)
ma[nx][ny]=t;
else
ma[nx][ny]=min(t,ma[nx][ny]);
}
}
}
bfs();
}
}