hdu 1548 A strange lift

http://acm.hdu.edu.cn/showproblem.php?pid=1548


这个题可以用搜索做,因为是求最短时间,搜索则直接想到广搜(BFS)。

问题:首先告诉你有n层楼,要你求从第A层楼到第B层楼的最短时间。

限制及条件:
1、每层楼只能按上或者下,而且上或者下的楼层数是不同的,需要输入的。
2、上下楼不能到达不存在的楼层(小于1楼或者大于n楼)。
3、1<=n,A,B<=200

AC代码:
#include<iostream>

#include<cstdio>

#include<queue>

#include<cstring>



using namespace std;



struct Node

{

    int f;

    int i;

};



int floor[210];

int yn[210];



int Bfs(int n, int a, int b)

{

    Node now,next;

    queue<Node> q;

    now.f = a;

    now.i = 0;

    q.push(now);

    while(!q.empty())

    {

        now = q.front();

        q.pop();

        yn[now.f] = 2;   //标记此楼已经到达

 //       printf("%d %d\n",now.f,now.i);

        if(now.f == b)   //判断是否到达指定楼层

        {

            return now.i;

        }

        else

        {

            next.i = now.i+1;

            next.f = now.f+floor[now.f];   //向上走

            if(next.f > 0 && next.f <= 200 && yn[next.f] == 0)

            {

                yn[next.f] = 1;   //标记此楼

                q.push(next);

            }

            next.f = now.f-floor[now.f];   //向下走

            if(next.f > 0 && next.f <= 200 && yn[next.f] == 0)

            {

                yn[next.f] = 1;   //标记此楼

                q.push(next);

            }

        }

    }

    return -1;

}



int main()

{

    int n,a,b;

    int i,num;

    while(scanf("%d",&n)&&n)

    {

        memset(yn,0,sizeof(yn));

        for(i = 0; i< 210; i++)

        {

            floor[i] = 1000;

        }

        scanf("%d%d",&a,&b);

        for(i = 1; i <= n; i++)

        {

            scanf("%d",&floor[i]);

        }

        num = Bfs(n,a,b);

        printf("%d\n",num);

    }



    return 0;

}



 

你可能感兴趣的:(HDU)