HDU - 1548 A strange lift

题目链接

题意

每层电梯有一个数字num,在第i层楼梯中你按了上,那么你就会到达i + num 层或者是 i - num 层,当然这个层数 >= 1 && <= n, 现在问你要从A层到达B层,最少需要按多少次按钮。

思路

基础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
#include <bits/stdc++.h>
using namespace std;
struct node{
int x,time;
};
int N,vis[201],f[201];
int bfs(int st,int ed)
{
int t;
node A,B;
queue<node>Q;
A.x = st;
A.time = 0;
Q.push(A);
vis[st] = 1;
while(!Q.empty())
{
A = Q.front();
Q.pop();
if(A.x == ed)
return A.time;
t = A.x + f[A.x];
if(!vis[t] && t >= 1 && t <= N)
{
vis[t] = 1;
B.x = t;
B.time = A.time + 1;
Q.push(B);
}
t = A.x - f[A.x];
if(!vis[t] && t >= 1 && t <= N)
{
vis[t] = 1;
B.x = t;
B.time = A.time + 1;
Q.push(B);
}
}
return -1;
}
int main()
{
int A,B;
while(cin >> N && N){
memset(vis,0,sizeof(vis));
cin >> A >> B;
for(int i = 1; i <= N; ++i)
{
cin >> f[i];
}
int c = bfs(A,B);
if(c == -1)
cout << "-1" << endl;
else
cout << c << endl;
}
}