题意
大楼的每一层楼都可以停电梯,而且第 层楼()上有一个数字 ()。电梯只有四个按钮:开,关,上,下。上下的层数等于当前楼层上的那个数字,求 楼到 楼按按钮次数的最小值
输出一行,即最少按键次数,若无法到达,则输出 -1
数据范围:对于 的数据,,,
思路
把每一层楼用结构体维护,然后广搜(bfs)即可
为了优化,我用STL里的queue(队列)优化
本题中会用的函数:
push():在队尾添加元素pop():弹出队首元素front():返回队首元素empty():判断队列是否为空
AC Code
杜绝control+c,control+v做题法,维护诚信洛谷
#include <iostream>
#include <queue>
using namespace std;
bool check[205];//辅助数组,记录是否来过该楼层
int step[205];
struct l{
int id, totalst;
}aa[205];
void bfs(int n, int a, int b){
if (a == b){
cout << 0;
return;
}
queue <l> q;
q.push((l){a, 0});
check[a] = true;
while (!q.empty()){
l x = q.front();
q.pop();
for (int i = -1; i <= 1; i += 2){//一个往上,一个往下,可以用循环优化
int y = x.id + i * step[x.id];
if (y < 1 || y > n || check[y])//边界
continue;
check[y] = true;/标记
if (y == b){//满足条件
cout << x.totalst + 1;
return;
}
q.push((l){y, x.totalst + 1});
}
}
cout << -1;//如果搜索完了没有退出,说明无解
}
int main() {
int n, a, b;
cin >> n >> a >> b;
for (int i = 1; i <= n; i++)
cin >> step[i];
bfs(n, a, b);
return 0;
}