Catch That Cow(BFS)

题目链接:

[kuangbin带你飞]专题一 简单搜索 - Virtual Judgehttps://vjudge.net/contest/65959#problem/C

求最短操作数问题, bfs水题。

#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
typedef long long ll;
const int maxn = 2e6;
int n, k;
queue<int> q;
bool vis[maxn]; // 是否遍历过该点
int cnt[maxn]; // 到该点的最小操作数

int bfs(){
    // 处理起点
    q.push(n);
    cnt[n] = 0;
    vis[n] = true;
    while(q.size()){
        int cur = q.front(); q.pop();
        int next;
        for(int i=0; i<3; i++){
            // 三种处理方式
            if(i == 0) next = cur + 1;
            else if(i == 1) next = cur - 1;
            else next = cur * 2;
            if(next < 0 || next >= maxn || vis[next]) continue; // 除去越界的元素,和遍历过的元素

            //处理当前next点
            q.push(next);
            vis[next] = true;
            cnt[next] = cnt[cur] + 1;
            if(next == k) return cnt[next];
        }
    }
    return -1; // 不可能到这里
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0); cout.tie(0);

    cin >> n >> k;
    if(n >= k) {cout << n-k << endl; return 0;} // 剪枝
    cout << bfs() << endl;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值