P2895. Meteor Shower S

考点

  • BFS

题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <bits/stdc++.h>

using namespace std;

const int LEN = 350;

int ans = -1, vis[LEN][LEN], table[LEN][LEN], walk[4][2] = {{-1, 0}, {0, -1}, {0, 1}, {1, 0}};

struct Node
{
int x_, y_, t_;
Node(int x, int y, int t) : x_(x), y_(y), t_(t) {}
};

queue<Node> q;

void init()
{
memset(table, -1, sizeof(table));
int n, x, y, t;
cin >> n;
while (n--)
{
cin >> x >> y >> t;
//坑点,同一位置可能有数次流星
if (table[x][y] == -1)
table[x][y] = t;
else
table[x][y] = min(t, table[x][y]);
for (int i = 0; i < 4; ++i)
{
int nxt_x = x + walk[i][0], nxt_y = y + walk[i][1];
if (nxt_x < 0 || nxt_y < 0)
continue;
table[nxt_x][nxt_y] = table[nxt_x][nxt_y] == -1 ? t : min(table[nxt_x][nxt_y], t);
}
}
q.emplace(0, 0, 0);
vis[0][0] = 1;
}

void bfs()
{
while (!q.empty())
{
Node u = q.front();
q.pop();
int ux = u.x_, uy = u.y_, ut = u.t_;
if (table[ux][uy] == -1)
{
ans = ut;
return;
}
for (int i = 0; i < 4; ++i)
{
int x = ux + walk[i][0], y = uy + walk[i][1], t = ut + 1;
if (x < 0 || y < 0 || vis[x][y] || (table[x][y] != -1 && table[x][y] <= t))
continue;
q.emplace(x, y, t);
vis[x][y] = 1;
}
}
}

int main()
{
init();
bfs();
cout << ans << endl;
return 0;
}

思路

根据题眼最少需要多少时间到达一个安全的格子,求步骤最少的解自然是BFS;本题蕴藏着相当多的细节

  1. 不要省标记数组。

    在地区被炸之前,你是可以自由出入它的;所以不能将坠落时间直接赋值到标记数组上

    仍需要额外建立一个标记数组来控制程序不要回头

  2. 同一个地方流星会掉数次。

    每一片地区都有可能被炸数次,所以每次更新坠落点及其周围区域的坠落时间时,都要取最小值

  3. 牛是可以跑出牧场的。

    题眼提到她只能在第一象限中,平行于坐标轴行动

    也就是说,牛的横纵坐标不能为负数,但是正数取值并没有限制

    尽管题目给了横纵坐标各300的取值限制,但如果能从坐标轴上方或右方逃离牧场,也算解

整理上述细节后,本题就没有难点啦~