A strange lift Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 8236    Accepted Submission(s): 3129


Problem Description
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
 

Recommend
8600

解题思路:这是一道比较明显的广度优先搜索题目,最少次数。和一般的广搜不同的是,化二维为一位,也因此简化了解题过程。
                解题时,直接从2个方向搜索即可,没有刁难的地方。只有一点,与平常思维不同:电梯只能按上下键,不同的楼层得到的变化情况也不尽相同,这里一定要打破常规思维,严格按题目做题,不然,就一边纠结去吧!

#include<cstdio> #include<cstring> #include<queue> using namespace std; int map[200];   //电梯能运行的情况 层数 int flood[200]; //电梯停靠情况 是否停靠过,0,1 int dir[2]={1,-1};  // 电梯运行方向,向上,向下 int n,s,e; struct node {   int x;   int step; }; int bfs() {     node now,next;     queue<node> q;     now.x=s;     now.step=0;     flood[s]=1;     if(e==s)         return 0;     q.push(now);     while(!q.empty())     {         now=q.front();         q.pop();         for(int i=0;i<2;i++)     //向上或向下运行         {             next.x=now.x+dir[i]*map[now.x];             next.step=now.step+1;             if(next.x>=0&&next.x<n&&!flood[next.x])    //该层可停靠             {                 if(next.x==e)     //到达目的层                     return next.step;                 flood[next.x]=1;                 q.push(next);             }         }     }     return -1; } int main() {     int i;     while(scanf("%d",&n)&&n)     {         scanf("%d%d",&s,&e);         s--;   //数据与数据结构存储统一         e--;         memset(flood,0,sizeof(flood));         for(i=0;i<n;i++)             scanf("%d",&map[i]);         printf("%d\n",bfs());     }     return 0; }