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 meteori 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
* Line 1: The minimum time it takes Bessie to get to a safe place or -1 if it is impossible.
sample input4
0 0 2
2 1 2
1 1 2
0 3 5
sampleoutput
5
首先說一下這道題目的大概意思,Bessie從原點出發,然後有N個流星會在某個時刻落下,它們會破壞砸到的這個方格還會破壞
四邊相鄰的方塊,輸出多少時間之後他可以到達安全的地方。如果可能,輸出最優解,不可能則輸出-1。
分析:這道題目通過廣搜算法來解決,但是還是需要判重,不然會TLE。還有一個要注意的是,他可能一開始就被炸到。
#include<iostream>
#include<cstring>
#include<queue>
#include<cmath>
#include<algorithm>
using namespace std;
int map[340][340];
int dx[5]={0,0,0,1,-1};
int dy[5]={0,1,-1,0,0};
struct nod{
int x,y,t;
};
int bfs(){
if(map[0][0]==0)
return -1;
if(map[0][0]==-1)
return 0;
nod tmp,now;
tmp.x=tmp.y=tmp.t=0;
queue<nod> Q;
Q.push(tmp);
while(!Q.empty()){
now=Q.front();
Q.pop();
for(int i=1;i<5;i++){
tmp.x=now.x+dx[i];
tmp.y=now.y+dy[i];
tmp.t=now.t+1;
if(tmp.x<0||tmp.y<0||tmp.x>=350||tmp.y>=350)
continue;
if(map[tmp.x][tmp.y]==-1)//找到安全地帶退出
return tmp.t;
if(tmp.t>=map[tmp.x][tmp.y])//到達改點的時間大於等於被毀壞的時間都不行
continue;
map[tmp.x][tmp.y]=tmp.t;//更新走到改點的短時間
Q.push(tmp);
}
}
return -1;
}
int main()
{
int m,x,y,t;
while(cin>>m)
{
memset(map,-1,sizeof(map)); //初始化爲-1
while(m--){
cin>>x>>y>>t; //輸入點
int tmpx,tmpy;
for(int i=0;i<5;i++)
{//構建地圖
tmpx=x+dx[i],tmpy=y+dy[i];
if(tmpx<0||tmpx>=340||tmpy<0||tmpy>=340)
continue;
if(map[tmpx][tmpy]==-1)
map[tmpx][tmpy]=t;
else
map[tmpx][tmpy]=min(map[tmpx][tmpy],t);
}
}
cout<<bfs()<<endl;
}
}