您的位置:首页 > 其它

POJ3278 Catch That Cow

2014-07-17 21:04 441 查看
/*algorithm : BFS*/
#include <iostream>
#include <cstring>
#include <queue>
#include <algorithm>
#include <fstream>

using namespace std;

const int maxn = 100005;
int n, k;
int vis[maxn], step[maxn];

void BFS()
{
queue<int> q;
int head, next;
vis
= true;
step
= 0;
q.push(n);
while (!q.empty()) {
head = q.front();
q.pop();

for (int i = 0; i < 3; ++i) {

if (i == 0) next = head - 1;
if (i == 1) next = head + 1;
if (i == 2) next = head * 2;

if (next < 0 || next >= maxn) continue;
if (!vis[next]) {
vis[next] = true;
step[next] = step[head] + 1;
q.push(next);
}

if (next == k) {
cout << step[next] << endl;
return;
}
}
}
}

int main()
{
while (cin >> n >> k) {
memset(vis, 0, sizeof(vis));
memset(step, 0, sizeof(step));

BFS();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: