您的位置:首页 > 其它

poj 3278 Catch That Cow bfs

2016-02-28 13:04 357 查看

题目

题目链接: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
;
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
= 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: