Description
呵呵,有一天我做了一个梦,梦见了一种很奇怪的电梯。大楼的每一层楼都可以停电梯,而且第 i 层楼(1≤i≤N)上有一个数字 Ki(0≤Ki≤N)。电梯只有四个按钮:开,关,上,下。上下的层数等于当前楼层上的那个数字。当然,如果不能满足要求,相应的按钮就会失灵。例如:3,3,1,2,5 代表了Ki(K1=3,K2=3,……),从 1 楼开始。在 1 楼,按“上”可以到 4 楼,按“下”是不起作用的,因为没有−2 楼。那么,从 A 楼到 B 楼至少要按几次按钮呢?
Input
共二行。
第一行为三个用空格隔开的正整数,表示N,A,B(1≤N≤200,1≤A,B≤N)。
第二行为 N 个用空格隔开的非负整数,表示Ki。
Output
一行,即最少按键次数,若无法到达,则输出 -1
。
Sample 1
Inputcopy | Outputcopy |
---|---|
5 1 5 3 3 1 2 5 | 3 |
Hint
对于 100%的数据,1≤N≤200,1≤A,B≤N,0≤Ki≤N。
本题共 16个测试点,前 15 个每个测试点 6分,最后一个测试点10 分。
题目分析
本来想通过dfs来做这道题,交了几次发现总是超时,尝试剪枝结果还是卡了几个时间;最后只能用bfs了;
原理:视A楼层为起点,同时或许有上,下两种选项(判定是否符合题意),简单画图可以看出这是一个二叉树,此时一层一层进行搜索,最早搜索到的即为最短次数
代码示例
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
using ll = long long;
const int N = 1e5 + 10;
typedef struct queue{
int x, y; //楼层,按键次数(二叉树深度)
}que;
int n, a, b;
int g[N];
bool st[N]; //是否到过这一层
que q[N];
int res;
int bfs() {
if(a == b) return 0; //有一个样例卡着
int hh, tt;
q[0] = {a, 0};
hh = 0, tt = 1;
while(hh < tt) {
que t = q[hh];
int t1 = t.x + g[t.x], t2 = t.x - g[t.x]; //上,下楼
if(t1 >= 1 && t1 <= n && !st[t1]) {
st[t1] = 1;
if(t1 == b) return t.y + 1;
q[tt++] = {t1, t.y + 1};
}
if(t2 >= 1 && t2 <= n && !st[t2]) {
st[t2] = 1;
if(t2 == b) return t.y + 1;
q[tt++] = {t2, t.y + 1};
}
hh++;
}
return -1;
}
int main() {
scanf("%d %d %d", &n, &a, &b);
for(int i = 1; i <= n; i++) scanf("%d", &g[i]);
printf("%d\n", bfs());
return 0;
}