P2895 [USACO08FEB]Meteor Shower S
题目描述
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题,要求最短时间,所以用队列记录;
陨石地图用一个二维数组记录,内容为砸下时间,以时间早为标准;再用一个二维数组记录每个点最短时间;
终止条件:如果搜到一个点永远不会被陨石砸到,输出该点时间,或者直到搜索结束也没有出去,输出-1
1.流星定时砸下;
2.流星砸下时间已最早的那个为准
3.如果出不去要输出-1
要注意:
记录流星落下的地方,后面的时间不能直接覆盖前面的。
只有当这颗流星到达的时间小于前面流星到达的时间,才能把时间赋值给数组,而不能直接覆盖。
#include<bits/stdc++.h>
using namespace std;
struct node{//x,y存坐标,time存当前时间
int x,y,time;
};
int dx[]={1,0,0,-1};
int dy[]={0,1,-1,0};
int times[305][305];//存这个格子流星到达的最早时间
bool vis[305][305];//判断这个点是否走过
int m,x,y,t;//m组数据
queue<node> Q;
int main(){
cin>>m;
memset(times,-1,sizeof times);//先将所有点时间初始化为-1
for(int i=1;i<=m;i++){
cin>>x>>y>>t;
if(times[x][y]==-1||t<times[x][y])
//如果这个点没有到达过,或者当前流星到达时间小于前面流星的到达时间,才能覆盖这个格子的时间
times[x][y]=t;
for(int i=0;i<4;i++){//这个流星的四周都不能走
int tx=x+dx[i],ty=y+dy[i];
if(tx>=0&&ty>=0&&(times[tx][ty]==-1||t<times[tx][ty]))//同上
times[tx][ty]=t;
}
}
node p;//起点
p.x=0,p.y=0,p.time=0;
vis[0][0]=true;
Q.push(p);
while(!Q.empty()){
p=Q.front();
Q.pop();
for(int i=0;i<4;i++){
int tx=p.x+dx[i],ty=p.y+dy[i];
if(tx>=0&&ty>=0&&!vis[tx][ty]&&(times[tx][ty]==-1||p.time+1<times[tx][ty]))
//即将到达的那个格子没有流星或者到达的时候流星还没到达
{
node next;
next.x=tx,next.y=ty;
next.time=p.time+1;
vis[tx][ty]=true;
Q.push(next);
if(times[tx][ty]==-1){//如果即将到达的格子安全
cout<<next.time<<endl;
return 0;
}
}
}
}
cout<<-1;//到不了安全的格子
return 0;
}