HDU 1548 A strange lift (BFS)

网友投稿 622 2022-08-23

HDU 1548 A strange lift (BFS)

HDU 1548  A strange lift (BFS)

A strange lift

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 20099    Accepted Submission(s): 7399

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   |   We have carefully selected several similar problems for you:  ​​1385​​​ ​​1142​​​ ​​1217​​​ ​​2066​​​ ​​1874​​

题解:有一个电梯,问你从A到B要按多少次 up 和 down 。

楼可以up或down 2层,在五楼可以up或down 5层.  (构造像并查集)。

AC代码; BFS

#include#include#include#includeusing namespace std;int flag[250],floor[250],N,A,B;struct node{ int step; int num;};int bfs(int A,int B){ int up,down; node temp,st; st.step=A; st.num=0; flag[A]=1; queueq; q.push(st); while(!q.empty()) { temp=q.front(); q.pop(); if(temp.step == B) { return temp.num; } up = temp.step+floor[temp.step]; down=temp.step-floor[temp.step]; if(!flag[up] && up<=N) { flag[up]=1; st.step=up; st.num=temp.num+1; //计数 q.push(st); } if(!flag[down] && down>0) { flag[down]=1; st.step=down; st.num=temp.num+1; //计数 q.push(st); } } return -1;}int main(){ while(cin>>N && N) { memset(flag,0,sizeof(flag)); scanf("%d%d",&A,&B); for(int i=1; i<=N; i++) { scanf("%d",&floor[i]); } printf("%d\n",bfs(A,B)); } return 0;}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:linux 统计指定进程内存使用情况到文件 脚本
下一篇:我爱写代码:编程语言了解(喜欢写代码)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~