题目链接: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): 7775 Accepted Submission(s): 2926
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
简单BFS搜索,但是我却脑残的错了好几次,主要是因为判断终点那出问题了,现在还没搞懂为啥错了。。。。
贴下代码:
1 #include<iostream> 2 #include<cstdio> 3 #include<queue> 4 using namespace std; 5 int g[204], vis[204], a, b, n; 6 struct node 7 { 8 int op; 9 int num; 10 }; 11 void getdata() 12 { 13 int i; 14 for(i = 1; i <= n; i++) 15 scanf("%d", &g[i]); 16 } 17 void bfs() 18 { 19 queue<node>q; 20 node p, s; 21 memset(vis, 0, sizeof(vis)); 22 p.op = 0; 23 p.num = a; 24 vis[a] = 1; 25 q.push(p); 26 while(!q.empty()) 27 { 28 p = q.front(); 29 q.pop(); 30 if(p.num == b) 31 { 32 printf("%d\n", p.op); 33 return ; 34 } 35 s.num = p.num + g[p.num]; 36 if(s.num <= n && s.num >= 1 && !vis[s.num]) 37 { 38 s.op = p.op + 1; 39 vis[s.num] = 1; 40 q.push(s); 41 } 42 s.num = p.num - g[p.num]; 43 if(s.num <= n && s.num >= 1 && !vis[s.num]) 44 { 45 s.op = p.op + 1; 46 vis[s.num] = 1; 47 q.push(s); 48 } 49 } 50 printf("-1\n"); 51 } 52 int main() 53 { 54 while(scanf("%d", &n) != EOF && n) 55 { 56 scanf("%d %d", &a, &b); 57 getdata(); 58 bfs(); 59 } 60 return 0; 61 }