练习二 1013 升降机问题

来源:互联网 发布:开淘宝客有用吗 编辑:程序博客网 时间:2024/04/27 15:57


题目大意:

         给出楼层总数,给出起始位置和终点位置。  然后现在 你在一个升降机里面,只能按 上升或者下降,给出  处在每层的时候  升降机运动的层数。也就是说,看样例:

现在处在  1  楼 ,要去  5楼。在  1 楼不可以按 下降,因为不可以降落到 -2 层。如果上升的话,会上升到  4  。也就是说上升或者下降越界的话,就不可以执行。

问 从起点到终点需要的最短次数。如果怎样都到不了没输出 -1


思路:


      此题为搜索典型题,从起点进行bfs即可,然后分为上下两种状态。


感想:


      这个题都是套路,哈哈


代码如下:

#include<iostream》
#include<queue>
#include<iomanip>
#include<cstdio>
using namespace std;
struct node
{
    int x;
    int t;
};
int main()    
{
    int ww[2000],c[2000];
    node first,next,m;
    queue<node> q;
    int n,a,b,i,e;

    while(cin>>n&&n!=0)
    {
        memset(c,0,sizeof(c));
        cin>>a>>b;
        for(i=1;i<=n;i++)
        {
            cin>>ww[i];c[i]=0;
        }
        e=0;
        first.x=a;
        first.t=0;
        q.push(first);
        c[first.x]=1;
        while(!q.empty())
        {
            m=q.front();
            q.pop();
            if(m.x==b)
            {
                e=1;break;
            }
            first.x=m.x-ww[m.x];
            next.x=m.x+ww[m.x];
            if(first.x>0&&first.x<=b&&!c[first.x])
            {
                first.t=m.t+1;
                c[first.x]=1;
                q.push(first);
            }
            if(next.x>0&&next.x<=b&&!c[next.x])
            {
                next.t=m.t+1;
                c[next.t]=1;
                q.push(next);
            }
        }
        while(!q.empty())
        {
            q.pop();
        }
        if(e)
   cout<<m.t<<endl;
        else
   cout<<"-1"<<endl;
    }
    return 0;
}


ACID:00757911




0 0