http://poj.org/problem?id=3669
流星掉下来会砸毁上下左右中五个点。每个流星掉下的位置和时间都不同,求能否活命,如果能活命,最短的逃跑时间是多少?
思路:对流星雨排序,然后将地图的每个点的值设为该点最早被炸毁的时间。如果起点一开始就被炸毁了的话,就死了,否则bfs。
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
int m[400][400];
int N;
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};
struct node{
int x;
int y;
int t;
};
int bfs(){
if (m[0][0]==0) return -1;
if (m[0][0]==-1) return 0;
node now,temp;
temp.x=temp.y=temp.t=0;
queue <node> q;
q.push(temp);
while (!q.empty()){
now=q.front();
q.pop();
for (int i=0;i<4;i++){
temp.x=now.x+dx[i];
temp.y=now.y+dy[i];
temp.t=now.t+1;
if (temp.x>=0&&temp.x<=400&&temp.y>=0&&temp.y<=400){
if (m[temp.x][temp.y]==-1) return temp.t;
if (temp.t<m[temp.x][temp.y]){
m[temp.x][temp.y]=temp.t;
q.push(temp);
}
}
}
}
return -1;
}
int main(){
int x,y,t;
cin >> N;
memset(m,-1,sizeof(m));
for (int i=1;i<=N;i++){
cin >> x >> y >> t;
if (m[x][y]==-1) m[x][y]=t;
for (int j=0;j<4;j++){
int xx=x+dx[j];
int yy=y+dy[j];
if (xx>=0&&xx<=400&&yy>=0&&yy<=400&&(m[xx][yy]>t||m[xx][yy]==-1)){
m[xx][yy]=t;
}
}
}
cout << bfs() << endl;
return 0;
}