天天看點

hdu1548 A strange lift (簡單bfs)A strange lift

題目連結:http://acm.hdu.edu.cn/showproblem.php?pid=1548

A strange lift

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 15974    Accepted Submission(s): 5973

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

【題意】

一個奇怪的電梯,每一層有一個數Ki,在每一層有兩個選擇,選擇上升Ki層,或者下降Ki層,現在給你起始層數 和目标層數,問最少幾次操作電梯能到達目标層數

如果不能則輸出-1;

【tips】

筆者wa的原因是沒考慮周全,忘了測試當起始層數 和目标層數相同時的情況。

【bfs代碼】

#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
int k[250];		int t;
int A,B;
bool vis[250];
struct node{
	int x,times;
}no;
int bfs(int a){
	queue<node>Q;
	while(!Q.empty())
		Q.pop();
	no.x=a;no.times=0;
	Q.push(no);
	vis[no.x]=1;
	while(!Q.empty()){
		node now=Q.front();
		Q.pop();
		if(now.x==B)
			return now.times; //在開始加上判斷條件 就ac了
		for(int i=0;i<2;i++){
			node next;
			if(i==0){
				next.x=now.x+k[now.x-1];  //上升
			}
			else if(i==1){
				next.x=now.x-k[now.x-1]; //下降
			}
			if(next.x>=1&&next.x<=t&&!vis[next.x]){
				next.times=now.times+1;
				vis[next.x]=1; //到達過的層數直接标記就可以了, 因為如果再回到該層就循環了
				if(next.x==B)
					return next.times;
				else
				{
					Q.push(next);
				}
			}
		}
	}
	return -1;
}
int main(){
	while(cin>>t&&t){
		memset(vis,0,sizeof(vis));
		cin>>A>>B;
		for(int i=0;i<t;i++){
			cin>>k[i];
		}
		int ans=bfs(A);
		cout<<ans<<endl;
	}
	return 0;
}
           

轉載于:https://www.cnblogs.com/chaiwenjun000/p/5320998.html