HDU1548 A strange lift 奇怪的电梯(BFS+队列)

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"? 
InputThe 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. OutputFor 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

分析:

题意:电梯在每一层都有一个数k,只能往上k层或者往下k层。让你求从m层到n层至少需要嗯多少次电梯按钮。
1.最短路的变行问题,将层数看做点,能够互相到达的层看做路径。
2.也可以用广搜做,搜索到达的路径。


#include
#include
#include
#include
#include
#include
#include
using namespace std;
const int MAX = 11000;
struct Node
{
    int to,step;
} node,nextnode;
int  v[MAX],f[MAX];
int main()
{
    int cas,n,m,i;
    while(scanf("%d",&cas)&&cas)
    {
        scanf("%d%d",&m,&n);
        memset(v,0,sizeof(v));
        for(i=1; i<=cas; i++)
            scanf("%d",&f[i]);//输入每层可以上下的层数
        queuequ;//定义队列
        while(!qu.empty())
        {
            qu.pop();
        }
        int  t1,t2,flag=0;
        node.step=0;//起始点
        node.to=m;
        qu.push(node);
        v[node.to]=1;
        while(!qu.empty())
        {
            node = qu.front();//取出首元素
            qu.pop();
            if(node.to == n)//如果到达终点
            {
                printf("%d\n",node.step);
                flag=1;
                break;
            }
            t1=node.to+f[node.to];//向上走
            if(t1<=cas&&!v[t1])
            {

                v[t1]=1;
                nextnode.to=t1;
                nextnode.step=node.step+1;
                qu.push(nextnode);
            }
            t1=node.to-f[node.to];//向下走
            if(t1>=1&&!v[t1])
            {
                v[t1]=1;
                nextnode.to=t1;
                nextnode.step=node.step+1;
                qu.push(nextnode);
            }
        }
        if(!flag)//如果走不到
            printf("-1\n");
    }
    return 0;
}


你可能感兴趣的:(搜索)