您的位置:首页 > 其它

Poj_3278 Catch That Cow(BFS)

2016-12-20 19:59 399 查看
题意:

约翰在N,牛在K。约翰可以花一分钟从x走到x+1,x-1或者2*x。问约翰最少花多少时间找到牛。

思路:

最少时间,想到用BFS。用结构体存储约翰的状态(pos,time),TLE了之后又开了一个数组标记到过的点,然后AC。这道题好像做过。。。

代码实现:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <queue>

using namespace std;

const int MAX = 100010;

struct Node{
int pos;
int times;
Node(int pos,int times){
this->pos = pos;
this->times = times;
};
Node(){}
};

int N,K;
int res;
bool tag[MAX];
queue<Node> que;
int main()
{
scanf("%d%d",&N,&K);
res = 0;
Node tmp;
tmp.pos = N;
tmp.times = 0;
que.push(tmp);
memset(tag,false,sizeof(tag));
while( !que.empty() ){
tmp = que.front();
que.pop();
if( tag[tmp.pos] == true ){
continue;
}
tag[tmp.pos] = true;
if( tmp.pos == K ){
res = tmp.times;
break;
}
if( tmp.pos+1 < MAX ){
que.push(Node(tmp.pos+1,tmp.times+1));
}
if( tmp.pos-1 >= 0 ){
que.push(Node(tmp.pos-1,tmp.times+1));
}
if( tmp.pos*2 < MAX ){
que.push(Node(tmp.pos*2,tmp.times+1));
}
}
printf("%d\n",res);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  poj bfs