这道题的意思就是有一个n成楼的电梯,每层楼都有一个数字ki表示从这一楼可以上当前楼层数加上ki楼,或者下当前楼层数减去ki,
题目描述:There is a strange lift.The lift can stop can at every floor as you want, and there is a number Ki(0 <= Ki <= N) on every floor.The lift have just two buttons: up and down.When you at floor i,if you press the button “UP” , you will go up Ki floor,i.e,you will go to the i+Ki th floor,as the same, if you press the button “DOWN” , you will go down Ki floor,i.e,you will go to the i-Ki th floor. Of course, the lift can’t go up high than N,and can’t go down lower than 1. For example, there is a buliding with 5 floors, and k1 = 3, k2 = 3,k3 = 1,k4 = 2, k5 = 5.Begining from the 1 st floor,you can press the button “UP”, and you’ll go up to the 4 th floor,and if you press the button “DOWN”, the lift can’t do it, because it can’t go down to the -2 th floor,as you know ,the -2 th floor isn’t exist.
Here comes the problem: when you are on floor A,and you want to go to floor B,how many times at least he has to press the button “UP” or “DOWN”?
Input
The input consists of several test cases.,Each test case contains two lines.
The first line contains three integers N ,A,B( 1 <= N,A,B <= 200) which describe above,The second line consist N integers k1,k2,…kn.
A single 0 indicate the end of the input.
Output
For each case of the input output a interger, the least times you have to press the button when you on floor A,and you want to go to floor B.If you can’t reach floor B,printf “-1”.
Sample Input
5 1 5
3 3 1 2 5
0
Sample Output
3
#include<stdio.h>
struct node
{
int x;
int s;
};
int main()
{
struct node que[20000];
int i,n,a,b,c[20000],next[2]={-1,1},head,tail,tx,t1,flag;
while(scanf("%d",&n),n!=0)
{
flag=0;
int book[20000]={0};//因为是多样例所以每次用之前要对标记数组置零
scanf("%d%d",&a,&b);//输入当前楼层数,和要去的楼层数
for(i=1;i<=n;i++)
scanf("%d",&c[i]);//将每层的ki存到数组里
if(a==b)
printf("0\n");//如果要去的楼层数跟当前楼层数,就不需要按上或按下,因此按上或者按下的的次数为零
else
{
head=1;
tail=1;
que[tail].x=a;
que[tail].s=0;
book[a]=1;
tail++;
while(head<tail)
{
for(i=0;i<2;i++)
{
t1=que[head].x;
tx=que[head].x+c[t1]*next[i];//当i=0时表示向上,i=1时表示向下,
if(tx<1||tx>n)
continue;
if(book[tx]==0)//如果这一层还没有到过
{
book[tx]=1;//就将其标记以防下次在到这一楼造成死循环
que[tail].x=tx;//降下一层的楼层数加入到队列
que[tail].s=que[head].s+1;
tail++;
}
if(tx==b)
{
flag=1;
break;
}
}
if(flag==1)
break;
head++;
}
if(flag==0)//如果不能到达的话就输出-1
printf("-1\n");
else
printf("%d\n",que[tail-1].s);
}
}
return 0;
}