kuangbin专题一 catch the cow (BFS)

BFS例题

注意:1. 超过100000时跳出 2. 如果到右边再回来,一定没有直接从左边过去划算

代码:

// zyc 2018/8/20

#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;

typedef long long ll;
const int maxn = 100000 + 7;
const int inf = 0x3f3f3f3f;

int m, k;
int dis [maxn];
bool cheak (int l)
{
    if (l >= 0 && l <= 100000 && dis[l] == inf) return true;
    else return false;
}
void bfs ()
{
    memset (dis, inf, sizeof (dis));
    int s1, s2;
    queue <int> res;
    dis[m] = 0;
    res.push(m);
    while (!res.empty()) {
        s1 = res.front ();
        if (s1 == k) {printf ("%d\n", dis[s1]); return ;}
        res.pop();
        s2 = s1;
        if (cheak (s2 + 1)) { dis[s2 + 1] = dis[s2] + 1; res.push(s2 + 1);}
        s2 = s1;
        if (cheak (s2 * 2)) { dis[s2 * 2] = dis[s2] + 1; res.push(s2 * 2);}
        s2 = s1;
        if (cheak (s2 - 1)) { dis[s2 - 1] = dis[s2] + 1; res.push(s2 - 1);}
    }
}
int main ()
{
    while (~scanf ("%d %d", &m, &k)) {
        bfs ();
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值