HDU

来源:互联网 发布:vb进度条控件使用 编辑:程序博客网 时间:2024/06/06 00:53

题目:

HDU - 1548 A strange lift

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


题意:

有一架电梯,在每层可以向上或者向下运行,不可以上天或入地但是在每层都是只能运行固定的楼层数,给出初始楼层和终点楼层以及在每层楼上可以运行的楼层数,要求我们找出是否能到达终点楼层。

分析:
这道题需要我们找出是否能到并且能到的时候输出步数,每层楼都至少有1个节点,至多有两个节点,从初始节点出发,看能否找到终点。那么用BFS来搜索就OK,注意的是使用访问数组,防止出现死循环访问的情况。


代码如下:

#include <cstdio>#include <iostream>#include <queue>#include <cstring>using namespace std;int ar[300];int n, a, b;bool vis[300];struct lift        //结构体存当前楼层数和最终的步数{    int f;    int step;};int bfs(int a){    int ans = -1;    queue<lift> qu;    qu.push(lift{a, 0});    while(!qu.empty())    {        lift m = qu.front();        qu.pop();        if(vis[m.f] == 1)        //如果访问过就继续,确保都是第一次到            continue;        vis[m.f] = 1;        //标记        if(m.f == b)        {            ans = m.step;        //如果到了的话就记录步数            break;        }        if(m.f - ar[m.f] > 0)        //下降在合理范围内        {            qu.push(lift{m.f - ar[m.f], m.step + 1});        }        if(m.f + ar[m.f] <= n)        //上升在合理范围内        {            qu.push(lift{m.f + ar[m.f], m.step + 1});        }    }    while(!qu.empty()) qu.pop();    return ans;}int main(){    while(cin >> n && n != 0)    {        cin >> a >> b;    //初始楼层和终点楼层        memset(ar, 0, sizeof(ar));    //初始化        memset(vis, 0, sizeof(vis));    //初始化        for(int i = 1; i <= n; i++)        {            cin >> ar[i];    //每层楼可以运行的楼层数        }        cout << bfs(a) << endl;    }    return 0;}