标签:acm hdu bfs 搜索
题目链接: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
Sample Output
【题意】
一个奇怪的电梯,每一层有一个数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;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
hdu1548 A strange lift (简单bfs)
标签:acm hdu bfs 搜索
原文地址:http://blog.csdn.net/chaiwenjun000/article/details/47311121