acm_A strange lift

来源:互联网 发布:洞箫f调制作数据图 编辑:程序博客网 时间:2024/06/04 19:10

题目:

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

题意:
给你一个起点楼层和终点楼层,在每一层都只能上升或下降该层数,比如。在三层那只能向上或向下走三层。。求最小次数到终点;

想法:
用广搜,这样貌似能形成一个二叉树,找到那个叶子节点就停止,一定为最小步数。。

代码:
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
int N, A, B;
int a[205];
bool map[205], flag;
struct node
{
    int x;
    int step;
};
void BFS()
{
    flag = false;
    node n1, n2, m;
    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!=0)
        cout<<m.step<<endl;
    else
        cout<<"-1"<<endl;
}
int main()
{
    int i;
    while ((cin>>N)&&(N!=0))
    {
        cin>>A>>B;
        memset(map,true,sizeof(map));
        for (i = 1; i <= N; i++)
        {
            cin>>a[i];
            map[i] = false;
        }
        BFS();
    }
    return 0;
}


0 0
原创粉丝点击