HDU-1548 A strange lift

来源:互联网 发布:阿里云计算认证考试 编辑:程序博客网 时间:2024/06/05 10:24

A strange lift

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

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,但是我发现在出队列的时候判断终点AC,在入队列的时候判断就会WA。后来才明白,如果起点就是终点的时候,入队列判断可能会输出-1。今后要改姿势!
代码如下:
/*ID: j.sure.1PROG:LANG: C++*//****************************************/#include <cstdio>#include <cstdlib>#include <cstring>#include <algorithm>#include <cmath>#include <stack>#include <queue>#include <vector>#include <map>#include <string>#include <climits>#include <iostream>#define INF 0x3f3f3f3fusing namespace std;/****************************************/const int N = 210;int n, from, to;bool vis[N];int dir[N];int bfs(){int fron = 0, rear = 0;int q[N][2];memset(vis, 0, sizeof(vis));vis[from] = true;q[rear][0] = from; q[rear++][1] = 0;while(fron < rear) {int t = q[fron%N][0], s = q[fron%N][1]; fron++;if(t == to) return s;for(int i = -1; i < 2; i+=2) {int nt = t + i*dir[t];if(nt >= 1 && nt <= n && !vis[nt]) { //if(nt == to) return s+1;//不加特判在这里返回就会WAvis[nt] = true;q[rear%N][0] = nt; q[rear%N][1] = s+1; rear++;}}}return -1;}int main(){#ifdef J_Sure//freopen("000.in", "r", stdin);//freopen(".out", "w", stdout);#endifwhile(scanf("%d", &n)!=EOF&&n) {scanf("%d%d", &from, &to);for(int i = 1; i <= n; i++) {scanf("%d", &dir[i]);}//if(from == to) printf("0\n");//加特判也可以避免WA//else printf("%d\n", bfs());}return 0;}


0 0
原创粉丝点击