hdu 1548 一维bfs大水题

本文通过一维BFS算法解决电梯从A到B楼的最短时间问题,详细解析并提供代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:

电梯,可以往上走或往下走,求从A到B楼的最短时间。


解析:

一维bfs,水。


代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <stack>
#include <vector>
#include <queue>
#include <map>
#define LL long long
#define lson lo, mi, rt << 1
#define rson mi + 1, hi, rt << 1 | 1

using namespace std;
const int maxn = 200 + 10;
const int inf = 0x3f3f3f3f;
const double eps = 1e-6;
const double pi = acos(-1.0);
const double ee = exp(1.0);

int n, fr, to;
int step[maxn];
int dp[maxn];

int bfs()
{
    memset(dp, -1, sizeof(dp));
    queue<int> q;
    q.push(fr);
    dp[fr] = 0;

    while (!q.empty())
    {
        int now = q.front();
        q.pop();

        if (now == to)
            return dp[now];

        int next = now + step[now];
        if (next <= n)
        {
            if (dp[next] == -1)
            {
                dp[next] = dp[now] + 1;
                q.push(next);
            }
        }
        next = now - step[now];
        if (1 <= next)
        {
            if (dp[next] == -1)
            {
                dp[next] = dp[now] + 1;
                q.push(next);
            }
        }
    }
    return -1;
}

int main()
{
#ifdef LOCAL
    freopen("in.txt", "r", stdin);
#endif // LOCAL

    while (~scanf("%d", &n))
    {
        if (!n)
            break;
        scanf("%d%d", &fr, &to);
        for (int i = 1; i <= n; i++)
            scanf("%d", &step[i]);
        printf("%d\n", bfs());
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值