搜索算法8之1014

1 題目編號:1014

2 題目內容:

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 &lt;= Ki &lt;= N) on every floor.The lift have just two buttons: up and down.When you at floor i,if you press the button &quot;UP&quot; , 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 &quot;DOWN&quot; , 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 &quot;UP&quot;, and you'll go up to the 4 th floor,and if you press the button &quot;DOWN&quot;, 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.<br>Here comes the problem: when you is on floor A,and you want to go to floor B,how many times at least he havt to press the button &quot;UP&quot; or &quot;DOWN&quot;?<br>
 

Input
The input consists of several test cases.,Each test case contains two lines.<br>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.<br>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<br>3 3 1 2 5<br>0
 

Sample Output
3
 

3 解題思路形成過程:有一個特別的電梯,第i層有一個對應的數字ki, 對於第i層按上升鍵up可升上到i+k[i]層,按下降鍵down到達i-k[i]層,到達的樓層最高不能超過n層,最低不能小於1層。給你一個起點A和終點B,問最少要按幾次上升鍵或者下降鍵到達目的地。把每一層都看成一個節點,問題就可以變成求起點到終點的最短路徑問題。用bfs廣搜,只要作一下標記去過的地方,不能再去即可。

4 代碼:#include <iostream>  
#include <stdio.h>  
#include <memory.h>  
#include <queue>  
using namespace std;


int N, A, B;
int a[205];
bool map[205], flag;


struct node
{
int x, step;
}n1, n2, m;


int main()
{
int i;
while (cin>>N)
{
if (N == 0) break;
cin >> A >> B;
for (i = 1; i <= N; i++)
{
cin >> a[i];
map[i] = false;
}
flag = false;
n1.x = A; n1.step = 0;
queue<node> Q;
Q.push(n1);
map[n1.x] = true;
while (!Q.empty())
{
m = Q.front();
Q.pop();
if (m.x == B)    //到達目標  
{
flag = true;
break;
}
n1.x = m.x - a[m.x];
n2.x = m.x + a[m.x];
if (n1.x>0 && n1.x <= B && !map[n1.x]) //下去的  
{
n1.step = m.step + 1;
map[n1.x] = true;   //標記  
Q.push(n1);
}
if (n2.x>0 && n2.x <= B && !map[n2.x]) //上去的  
{
n2.step = m.step + 1;
map[n2.x] = true;   //標記  
Q.push(n2);
}
}
if (flag) cout<<m.step<<endl;
else cout << "-1"<< endl;
}


return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章