题目描述
呵呵,有一天我做了一个梦,梦见了一种很奇怪的电梯。大楼的每一层楼都可以停电梯,而且第i层楼(1<=i<=N)上有一个数字Ki(0<=Ki<=N)。电梯只有四个按钮:开,关,上,下。上下的层数等于当前楼层上的那个数字。当然,如果不能满足要求,相应的按钮就会失灵。例如:3 3 1 2 5代表了Ki(K1=3,K2=3,……),从一楼开始。在一楼,按“上”可以到4楼,按“下”是不起作用的,因为没有-2楼。那么,从A楼到B楼至少要按几次按钮呢?
输入输出格式
输入格式:
输入文件共有二行,第一行为三个用空格隔开的正整数,表示N,A,B(1≤N≤200, 1≤A,B≤N),第二行为N个用空格隔开的正整数,表示Ki。
输出格式:
输出文件仅一行,即最少按键次数,若无法到达,则输出-1。
输入输出样例
输入样例#1:
LIFT.IN
5 1 5
3 3 1 2 5
输出样例#1:
LIFT.OUT
3
代码
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
#include<vector>
using namespace std;
struct cc{
int num,step;
}; cc make_cc(int num,int step){
cc a;
a.num=num;a.step=step;
return a;
} int a[],vis[],N,A,B,cnt;
queue<cc> que;
int main(){
// freopen("01.in","r",stdin);
// freopen("01.out","w",stdout); scanf("%d%d%d",&N,&A,&B);
for(int i=;i<=N;i++){
scanf("%d",&a[i]);
} que.push(make_cc(A,));
vis[A]=;
while(!que.empty()){
cc tmp=que.front();que.pop(); if(tmp.num==B){
printf("%d\n",tmp.step);
return ;
} int low=tmp.num-a[tmp.num],high=tmp.num+a[tmp.num]; if(low>= && !vis[low]){
que.push(make_cc(low,tmp.step+));vis[low]=;
}
if(high<=N && !vis[high]){
que.push(make_cc(high,tmp.step+));vis[high]=;
}
} puts("-1"); // fclose(stdin);
// fclose(stdout);
return ;
}正解
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
#include<vector>
using namespace std;
int a[],vis[],N,A,B,cnt;
queue<int> que;
int main(){
// freopen("01.in","r",stdin);
// freopen("01.out","w",stdout); scanf("%d%d%d",&N,&A,&B);
for(int i=;i<=N;i++){
scanf("%d",&a[i]);
} que.push(A);
vis[A]=;
while(!que.empty()){
int tmp=que.front();que.pop();
int low=tmp-a[tmp],high=tmp+a[tmp]; if(tmp==B){
printf("%d\n",cnt);
return ;
} if(low>&&!vis[low]){
que.push(low);vis[low]=;
}
if(high<=N&&!vis[high]){
que.push(high);vis[high]=;
}
cnt++;
} puts("-1"); // fclose(stdin);
// fclose(stdout);
return ;
}错误代码
错误代码是没有考虑到cnt可能不符合当前的步数
因为没理解好bfs导致错误,cnt一直增加,而步数是随bfs深度增加的