Bessie听说有场史无前例的流星雨即将来临;有谶言:陨星将落,徒留灰烬。为保生机,她誓将找寻安全之所(永避星坠之地)。目前她正在平面坐标系的原点放牧,打算在群星断其生路前转移至安全地点。
此次共有M (1 ≤ M ≤ 50,000)颗流星来袭,流星i将在时间点Ti (0 ≤ Ti ≤ 1,000) 袭击点 (Xi, Yi) (0 ≤ Xi ≤ 300; 0 ≤ Yi ≤ 300)。每颗流星都将摧毁落点及其相邻四点的区域。
Bessie在0时刻时处于原点,且只能行于第一象限,以平行与坐标轴每秒一个单位长度的速度奔走于未被毁坏的相邻(通常为4)点上。在某点被摧毁的刹那及其往后的时刻,她都无法进入该点。
寻找Bessie到达安全地点所需的最短时间。
Input
* 第1行: 一个整数: M
* 第2..M+1行: 第i+1行包含由空格分隔的三个整数: Xi, Yi, and Ti
Output
* 仅一行: Bessie寻得安全点所花费的最短时间,无解则为-1。
Sample Input
4 0 0 2 2 1 2 1 1 2 0 3 5
Sample Output
5
思路:
自己制作地图,预处理流星,即将包括自身以及相邻位置值置t(t取最小值,因为一个位置可能受到多个流星影响)
然后就是简单的广搜就行
#include<iostream>
#include<cstdio>
#include<fstream>
#include<queue>
#include<vector>
#include<cstring>
#define MAX 310
#define INF 10000000
using namespace std;
int M;
int map[MAX][MAX];
int d[MAX][MAX];
int xi[5] = {-1,1,0,0,0};
int yi[5] = {0,0,-1,1,0};
typedef pair <int, int> P;
//广搜处理
int Bfs(){
if(map[0][0]==-1)//起始点没落过流星,这里安全,不用走
return 0;
if(map[0][0]==0)//起始点在时间t=0时就被落过流星,没开始走就挂了
return -1;
queue <P> que;
que.push(P(0,0));
d[0][0] = 0;
while(!que.empty()){
P p = que.front();
que.pop();
//逃离
if(map[p.first][p.second] == -1)
return d[p.first][p.second];
//四向遍历
for(int i=0; i<4; i++){
int nx = p.first + xi[i];
int ny = p.second + yi[i];
//在第一象限,第一次经过,到达上一个节点的时间小于被摧毁时间-1(还要走一步)或者不会被摧毁
if(nx>=0 && ny>=0 && d[nx][ny]==0 && (d[p.first][p.second]<map[nx][ny]-1 || map[nx][ny]==-1)){
que.push(P(nx, ny));
d[nx][ny] = d[p.first][p.second]+1;
}
}
}
return -1;
}
//测试函数
int main(){
cin >> M;
memset(map, -1, sizeof(map));
for(int i=0; i<M; i++){
int x, y, t;
cin >> x >> y >> t;
//自身及周围在时刻t被摧毁
for(int i=0; i<5; i++){
int a = x + xi[i];
int b = y + yi[i];
//在题目要求范围内记住最早被摧毁的时间
if(a>=0 && b>=0){
if(map[a][b]!=-1)
map[a][b] = min(t, map[a][b]);
else
map[a][b] = t;
}
}
}
cout << Bfs() << endl;
return 0;
}