poj 3278 Catch That Cow bfs

题目

题目链接:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=105944#overview

题目来源:2016寒假高年训练3

简要题意:+1 -1 *2三种操作问n最少多少步到m

题解

最基础的bfs,注意判断一些边界条件即可。

使用三个方式去搜,复杂度为线性。

代码

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <stack>
#include <queue>
#include <string>
#include <vector>
#include <set>
#include <map>

#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define sz(x) ((int)(x).size())
#define fi first
#define se second
using namespace std;
typedef long long LL;
typedef vector<int> VI;
typedef pair<int,int> PII;
// head
const int N = 1e5+5;
const int INF = 0x3f3f3f3f;

int a[N];
int n, k;

void insert(queue<int> &q, int x, int cur) {
    if (x > N || x < 0 || a[x] != INF) return;
    q.push(x);
    a[x] = a[cur]+1;
}

int main() {
    while (scanf("%d%d", &n, &k) == 2) {
        memset(a, INF, sizeof a);

        a[n] = 0;
        queue<int> q;
        q.push(n);
        while (!q.empty()) {
            int cur = q.front();
            q.pop();
            if (cur == k) break;
            insert(q, cur+1, cur);
            insert(q, cur-1, cur);
            insert(q, cur<<1, cur);
        }
        printf("%d\n", a[k]);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值