题目:奇怪的电梯
网址:https://www.luogu.com.cn/problem/P1135
题目描述
呵呵,有一天我做了一个梦,梦见了一种很奇怪的电梯。大楼的每一层楼都可以停电梯,而且第i层楼(1≤i≤N)上有一个数字Ki(0≤Ki≤N)。
电梯只有四个按钮:开,关,上,下。
上下的层数等于当前楼层上的那个数字。当然,如果不能满足要求,相应的按钮就会失灵。例如:3,3,1,2,5代表了Ki(K1=3,K2=3,…),从1楼开始。在1楼,按“上”可以到4楼,按“下”是不起作用的,因为没有−2楼。那么,从A楼到B楼至少要按几次按钮呢?
输入格式
共二行。
第一行为3个用空格隔开的正整数,表示N,A,B(1≤N≤200,1≤A,B≤N)。
第二行为N个用空格隔开的非负整数,表示Ki。
输出格式
一行,即最少按键次数,若无法到达,则输出−1。
输入输出样例
输入
5 1 5
3 3 1 2 5
输出
3
本次使用广度优先搜索。
状态为当前所在的层数h。按照操作特判超过边界,即楼层大于n或小于0,即可。
代码如下:
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<queue>
using namespace std;
const int maxn = 200 + 5;
bool vis[maxn];
int A, B, d[maxn] = {};
int n, a[maxn];
int bfs()
{
if(A == B) return 0;
queue <int> Q;
while(!Q.empty()) Q.pop();
memset(d, 0, sizeof(d));
memset(vis, false, sizeof(vis));
d[A] = 0;
vis[A] = true;
Q.push(A);
int next;
while(!Q.empty())
{
int now = Q.front();Q.pop();
next = now + a[now];
if(next <= n)
{
if(!vis[next])
{
vis[next] = true;
d[next] = d[now] + 1;
if(next == B) return d[next];
Q.push(next);
}
}
next = now - a[now];
if(next > 0)
{
if(!vis[next])
{
vis[next] = true;
d[next] = d[now] + 1;
if(next == B) return d[next];
Q.push(next);
}
}
}
return -1;
}
int main()
{
scanf("%d %d %d", &n, &A, &B);
for(int i = 1; i <= n; ++ i) scanf("%d", &a[i]);
printf("%d
", bfs());
return 0;
}