HDU 1548 A strange lift

5 篇文章 0 订阅

原题链接:

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

题目大意:

输入N,A,B。分别表示有N层楼,最初楼层为A。终点楼层为B。然后是N个数表示在第i层楼按上或者下可以移动多少层。楼层不能超过N也不能低于1.
例如:
5 1 5
3 3 1 2 5
表示有5层楼,起点为1.终点为5。在3楼时。按下按钮可以上1层楼,或者下1层楼。

思路:

采用一般的bfs的方法既可以解得
一个数组存放访问标记是否到过这层楼。
一个数组存放到达这层楼的前一层楼是哪一层
越界判定和输出判定

代码如下:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>

using namespace std;

int N,A,B;
int Floor[205];
int Check[205];
int Pre[205];
int number;
int Up_Down[2]={ 1, -1 };
bool Can;

bool bIsLeagal(int Next )
{
    if( Next < 1 || Next > N )
        return false;
    return true;
}

void GetCount(int Index)
{
    while( Pre[ Index ] != -1 )
    {
        Index = Pre[ Index ];
        number++;
    }

}
void bfs()
{
    queue<int> check_floor;
    memset( Check,0,sizeof(Check));
    memset( Pre,0,sizeof( Pre ));
    Pre[A] = -1;
    Check[A] = true;
    check_floor.push ( A );

    int Now,Next;
    while( !check_floor.empty ())
    {
        Now = check_floor.front ();
        check_floor.pop ();
        if( Now == B )
        {
            Can = true;
            GetCount( Now );
            return;
        }
        int i;
        for( i = 0; i < 2; i++ )
        {
            Next = Now + Floor[Now] * Up_Down[i];
            if( bIsLeagal( Next ) && !Check[Next] )
            {
                Pre[Next] = Now;
                Check[Next] = true;
                check_floor.push ( Next );
            }

        }
    }
}
int main()
{
    while( cin >> N  )
    {
        if( N == 0 ) break;
        cin >> A >> B;
        Can = false;
        number = 0;
        memset( Floor,0,sizeof( Floor));
        int i;
        for( i = 1; i <= N; i++ )
            cin>> Floor[i];
        bfs();
        if( Can ) 
            cout<< number <<endl;
        else 
            cout<<-1<<endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值