A strange lift【BFS】

来源:互联网 发布:淘宝客定向计划链接 编辑:程序博客网 时间:2024/06/14 17:56

A strange lift

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


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 53 3 1 2 50

Sample Output
3
思路: 乍一看 觉得BFS和DFS 都是可以的但是 有个条件--- at least 至少 ,,就变成了最优解问题,,就必须要用 BFS了
还有这道题,,为什么也要设置V【】 数组呢?,,是因为如果第二次在到达同一层的话,,就会有循环...所以就和一般的BFS一样,不走已经走过的
代码
#include<stdio.h>#include<string.h>#include<algorithm>#include<queue>#define M 200+10 // 元素的总个数using namespace std;//  这个要在 设置 队列的前面  以后直接写在预处理的后面好了,,习惯 int v[M];// 必要 int floo[M];// 这是针对题的数组 int step[M];//  每一个元素 是在第几层--即 搜索了几次才找到的 int movex[2]={1,-1};//  可选方向的数组   move 是关键字,,最好不要用 int n;void bfs(int st,int ed){queue<int>num;int now,next;int exsit=0;v[st]=1;step[st]=0;num.push(st);while(!num.empty()){now=num.front();num.pop();if(now==ed)   //  结束的 条件 {exsit=1;break;}for(int i=0;i<2;i++) //  每个元素的可选的方向 (每个题也都不一样) {next=now+movex[i]*floo[now];if(!v[next]&&next>=1&&next<=n)  //  必有  方向成立的判定 (每个题都不一样) {//要逐个方向的判定,看是否可能合并,不行的话,就要单独得到写step[next]=step[now]+1;v[next]=1; num.push(next);}}if(exsit) printf("%d\n",step[ed]);else printf("-1\n"); }int main(){int st,ed;while(scanf("%d",&n)&&n){scanf("%d%d",&st,&ed);for(int i=1;i<=n;i++){scanf("%d",&floo[i]);v[i]=step[i]=0;  /// 初始化 }bfs(st,ed);return 0; } 
0 0
原创粉丝点击