A strange lift
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
完成AC
#include<stdio.h> #include<string.h> #include<iostream> #include<algorithm> #include<queue> #include<vector> using namespace std; const int MAX = 11000; struct Node//定义一个结构体关于 { int to,step; }; int v[MAX],f[MAX];//v用来标记楼层有没有走过 f存k[i] int main() { Node now,next; int cas,m,n,i; while(scanf("%d",&cas)&&cas)//cas表示几楼的数据 { scanf("%d%d",&m,&n);//m表示起点,n表示终点 memset(v,0,sizeof(v));//数组初始化 memset(f,0,sizeof(f)); for(i=1; i<=cas; i++) scanf("%d",&f[i]);//输入每层的数据 queue<Node>q;//定义队列 while(!q.empty())//清空队列 { q.pop(); } int t1,t2,flag=0; now.step=0;//起始点的步数 now.to=m; q.push(now);//把结点的情况输入 v[now.to]=1;//标记这个点已经走过了 while(!q.empty())// { now = q.front();//取出首元素 q.pop(); //下面是三种分类讨论:到达终点,向上走,向下走 if(now.to == n)//如果到达终点 { printf("%d\n",now.step); flag=1; break; } t1=now.to+f[now.to];//向上走 当前所在楼层数+该楼层可以移的层数 if(t1<=cas&&!v[t1])//条件的控制 没有超出总层数以及到的楼层没有被标记过 { v[t1]=1; next.to=t1; next.step=now.step+1; q.push(next); } t1=now.to-f[now.to];//向下走 if(t1>=1&&!v[t1])//下走最低为1 { v[t1]=1; next.to=t1; next.step=now.step+1; q.push(next); } } if(!flag)//如果走不到 flag==0 printf("-1\n"); } return 0; }