采用优先队列求解最少次数,也就是题目给你Ki,代表楼层数,你可以选择按下按钮,向上或者向下,最后选择最少的次数到达要去的楼层。
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
using namespace std;
const int maxx=205;
int vis[maxx];
int ans[maxx];
int n;
int A,B;
struct node{
int times;
int s;
bool friend operator<(const node a,const node b){
return a.times>b.times;
}
};
int bfs(int s){
priority_queue<node>q;
node a;
a.times=0;
a.s=s;
q.push(a);
vis[s]=1;
while(!q.empty()){
node u=q.top();
q.pop();
if(u.s==B){
return u.times;
}
for(int i=-1;i<=1;i+=2){
node t;
t.s=u.s+i*ans[u.s];
if(vis[t.s]==0&&t.s>0&&t.s<=n){
vis[t.s]=1;
t.times=u.times+1;
q.push(t);
}
}
}
return -1;
}
int main(){
while(cin>>n){
if(n==0)break;
cin>>A>>B;
for(int i=1;i<=n;i++){
scanf("%d",&ans[i]);
}
vis[A]=1;
memset(vis,0,sizeof(vis));
int flag=bfs(A);
if(flag!=-1){
cout<<flag<<endl;
}else{
cout<<-1<<endl;
}
}
return 0;
}