hdu 1548 A strange lift(搜索:BFS)

在每个楼层都有两种情况:或上或下

显然用bfs较容易找到最优路径

一直觉得自己搜索比较弱...结果没想到这么轻松就写下来了

一直坑的地方是忘了在输入数据后把队列清空了...

代码如下:

#include <cstdio>
#include <queue>
#include <cstring>
#include <iostream>
#include <algorithm>
#define MAXN 210
#define LL long long
using namespace std;

struct Floor {
    int k, cnt;
}c[MAXN];
queue<int> q;
int ans, n, b, vis[MAXN];

bool bfs() {
    int x, y;
    while(!q.empty()) {
        x = q.front();
        q.pop();
        if(x == b) {
            ans = c[x].cnt;
            return true;
        }
        
        y = x+c[x].k;
        if(y <= n && !vis[y]) {//避免陷入死循环
            q.push(y);
            vis[y] = 1;
            c[y].cnt = c[x].cnt+1;
        }

        y = x-c[x].k;
        if(y > 0 && !vis[y]) {
            q.push(y);
            vis[y] = 1;
            c[y].cnt = c[x].cnt+1;
        }
    }
    return false;
}

int main(void) {
    int a, i;
    while(scanf("%d", &n) && n) {
        scanf("%d%d", &a, &b);
        for(i=1; i<=n; ++i) {
            scanf("%d", &c[i].k);
            c[i].cnt = 0;
        }
        while(!q.empty())
            q.pop();
        memset(vis, 0, sizeof(vis));
        q.push(a);
        if(bfs()) {
            if(a == b)//看到别人说会出现要求到达的楼层比给出数据的n还大的情况...
                ans = 0;
            cout << ans << endl;
        }
        else cout << -1 << endl;
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值