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 DescriptionThere 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"?
InputThe 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.
OutputFor 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 53 3 1 2 50
Sample Output
3
Recommend8600
解題思路:這是一道比較明顯的廣度優先搜尋題目,最少次數。和一般的廣搜不同的是,化二維為一位,也因此簡化瞭解題過程。
解題時,直接從2個方向搜尋即可,沒有刁難的地方。只有一點,與平常思維不同:電梯只能按上下鍵,不同的樓層得到的變化情況也不盡相同,這裡一定要打破常規思維,嚴格按題目做題,不然,就一邊糾結去吧!
#include<cstdio>#include<cstring>#include<queue>using namespace std;int map[200]; //電梯能啟動並執行情況 層數int flood[200]; //電梯停靠情況 是否停靠過,0,1int 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;}