您的位置:首页 > 其它

poj 3278 Catch That Cow

2012-08-27 15:20 253 查看
#include <iostream>
#include <queue>
#include <memory.h>
using namespace std;
const int MAX = 100001;
int n, k, path[MAX];
bool vis[MAX];

void bfs()
{
int tmp;
queue<int> q;
//队列的初始化
while (q.size() != 0)
q.pop();

q.push(n);
path
= 0;
while (q.size() != 0){
tmp = q.front();
q.pop();
vis
= true;
if (tmp == k)   break;
else{
//第一种的做法,坐标减一
if (tmp - 1 >= 0){
if (!vis[tmp-1]){
q.push(tmp-1);
path[tmp-1] = path[tmp] + 1;
vis[tmp-1] = true;
}
}

//第二种的做法,坐标加一
if (tmp + 1 <= 100000){
if (!vis[tmp+1]){
q.push(tmp+1);
path[tmp+1] = path[tmp] + 1;
vis[tmp+1] = true;
}
}

//第三种做法,坐标乘以2
if (tmp * 2 <= 100000){
if (!vis[tmp*2]){
q.push(tmp*2);
path[tmp*2] = path[tmp] + 1;
vis[tmp*2] = true;
}
}
}
}
cout << path[k] << endl;
}

int main()
{
while (cin >> n >> k){
memset(path, 0, sizeof(path));
memset(vis, false, sizeof(vis));
bfs();
}

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