您的位置:首页 > 其它

POJ 3278 Catch That Cow (BFS)

2017-07-19 22:53 537 查看
沉默这么长时间, 躁动起来了;


B - Catch That Cow

 

题目大意:一个农民一头牛,都一个数轴上,牛在K不动.,农户开始在n位置。假设农户在M位置,每次移动时有三种选择方式:

1.移动到M-1

2.移动到M+1位置

3.移动到M*2的位置。

问最少移动多少次可以移动到牛所在的位置。

BFS搜三种状态, 结果就是;

注意N 的大小, 要大, 开小了 runtime error;

#include <cstring>
#include <iostream>
#include <queue>
#include <algorithm>
#include <stdio.h>
#include <cmath>
using namespace std;

const int N = 201000;
int n, k;
struct node
{
int x, y;
};
queue<node> Q;
int vis
;

void BFS()
{
int X, Y;
while(!Q.empty())
{
node temp = Q.front();
Q.pop();
X = temp.x;
Y = temp.y;
if(X == k)
{
printf("%d\n",Y);
return ;
}
if(X >= 1 && !vis[X - 1]) //脳麓脤卢脪禄 -1;
{
node te;
vis[X - 1] = 1;
te.x = X - 1;
te.y = Y + 1;
Q.push(te);
}
if(X <= k && !vis[X + 1])//脳麓脤卢+1
{
node te;
vis[X + 1] = 1;
te.x = X + 1;
te.y = Y + 1;
Q.push(te);
}
if(X <= k && !vis[X * 2])//脳麓脤卢*2
{
node te;
vis[X * 2] = 1;
te.x = 2 * X;
te.y = Y + 1;
Q.push(te);

c54e
}
}
}

int main()
{
while(~scanf("%d %d",&n,&k))
{
while(!Q.empty()) Q.pop();
memset(vis,0,sizeof(vis));
vis
= 1;
node t;
t.x = n, t.y = 0;
Q.push(t);
BFS();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: