题意大致是一群流星来袭,告诉你流星将要击中的坐标及到达时间(流星的作用范围是上下左右外加中间的点),要求你能否逃到安全区(是指没有被击中的地方)。
思路是建一个第一象限的直角坐标系(当然是用数组了(^-^)!),用数字在坐标系上标出到达时间,若流星毁灭的范围有交集,取最小的时间(因为要是最优解,你的目标是安全区,犯不着在流星撞击时旅游吧!)再写一个带时间的Bfs()就行了。
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
const int maxsize = 300 + 10;
const int maxmeteors = 50005;
const int INF = 100000000;
int map[maxsize][maxsize];
bool if_visited[maxsize][maxsize];//不重复访问同一个地方或不在原地逗留,保证Bfs得出的是最优解
int dir[5][2] = {
{1,0},{0,1},{-1,0},{0,-1},{0,0}
};
int the_num_meteor;
//int the_last_time;
//我认为没必要计算最终下落时刻,因为被流星击中的地方并不是目标地点
struct Node {
int x, y, fall_down_time;
};
Node the_meteors[maxmeteors];
int Bfs() {
queue<Node> que;
Node star;
star.x = 0; star.y = 0; star.fall_down_time = 0;
que.push(star);
if_visited[star.x][star.y] = true;
while (!que.empty()) {
Node now_step = que.front();
que.pop();
for (int i = 0; i < 4; i++) {
Node next_step = now_step;
next_step.x += dir[i][0];
next_step.y += dir[i][1];
next_step.fall_down_time++;
if (next_step.x >= 0 && next_step.y >= 0 && !if_visited[next_step.x][next_step.y]
&& map[next_step.x][next_step.y] > next_step.fall_down_time) {
if_visited[next_step.x][next_step.y] = true;
if (map[next_step.x][next_step.y] == INF) {
return next_step.fall_down_time;
}
que.push(next_step);
}
}
}
return -1;
}
void Init() {
for (int i = 0; i < maxsize; i++) {
for (int j = 0; j < maxsize; j++) {
map[i][j] = INF;
}
}
memset(if_visited, false, sizeof(if_visited));
for (int i = 0; i < the_num_meteor; i++) {
for (int j = 0; j < 5; j++) {
int move_x = the_meteors[i].x + dir[j][0];
int move_y = the_meteors[i].y + dir[j][1];
if (move_x >= 0 && move_y >= 0 && map[move_x][move_y] > the_meteors[i].fall_down_time) {
map[move_x][move_y] = the_meteors[i].fall_down_time;
}
}
}
}
int main() {
while (scanf("%d", &the_num_meteor) == 1) {
for (int i = 0; i < the_num_meteor; i++) {
scanf("%d%d%d", &the_meteors[i].x,&the_meteors[i].y,&the_meteors[i].fall_down_time);
}
//计算最终下落时刻
//for (int i = 0; i < the_num_meteor; i++) {
// if (i == 0) {
// the_last_time = the_meteors[i].fall_down_time;
// }
// else {
// the_last_time = max(the_last_time, the_meteors[i].fall_down_time);
// }
//}
Init();
if (map[0][0] == 0) {
printf("-1\n");
}
else {
printf("%d\n", Bfs());
}
}
return 0;
}
谢谢阅读(…^-^…)