题意:坐电梯,每次可以选着上下,对应移动的楼层是Ki,问从起点到终点最少要按几次。
AC代码:
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int maxn=205;
int n,a,b;
int d[maxn],p[maxn];
const int dx[]={-1,1};
int bfs(){
queue<int>q;
memset(d,-1,sizeof(d));
d[a]=0;
q.push(a);
while(!q.empty()){
int now=q.front();
q.pop();
if(now==b) return d[now];
for(int i=0;i<2;++i){
int w=now+dx[i]*p[now];
if(w<=0||w>n||d[w]!=-1) continue;
q.push(w);
d[w]=d[now]+1;
}
}
return -1;
}
int main(){
while(scanf("%d",&n)!=EOF&&n){
scanf("%d%d",&a,&b);
for(int i=1;i<=n;++i)
scanf("%d",&p[i]);
printf("%d\n",bfs());
}
return 0;
}
如有不当之处欢迎指出!