您的位置:首页 > 编程语言 > C语言/C++

Meteor Shower(广搜)

2017-08-13 13:34 120 查看
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

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

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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ meteor acm 广搜