P1135. 奇怪的电梯

考点

  • 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
#include <bits/stdc++.h>

using namespace std;

const int LEN = 250;

int N, A, B, ans = -1, dis[LEN], vis[LEN];

struct Node
{
int floor_, cnt_;
Node(int floor, int cnt) : floor_(floor), cnt_(cnt) {}
};

queue<Node> q;

void bfs()
{
while (!q.empty())
{
Node u = q.front();
q.pop();
int uf = u.floor_, uc = u.cnt_;
if (uf == B)
{
ans = uc;
break;
}
for (int i = -1; i <= 1; i += 2)
{
int f = uf + i * dis[uf];
if (f < 1 || f > N || vis[f])
continue;
vis[f] = 1;
q.emplace(f, uc + 1);
}
}
}

int main()
{
cin >> N >> A >> B;
for (int i = 1; i <= N; ++i)
cin >> dis[i];
q.emplace(A, 0);
vis[A] = 1;
bfs();
cout << ans;
return 0;
}

思路

根据题眼至少要按几次按钮,要找步骤最少的解当然是BFS

有两个注意点:

  • BFS不回头,所以走过的楼层就不再走,否则会导致死循环
  • 每次先判断当前楼层是否为答案,再枚举下一次的新状态