POJ 3278 Catch That Cow (BFS)


沉默这么长时间, 躁动起来了;

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[N];

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);
        }
    }
}

int main()
{
    while(~scanf("%d %d",&n,&k))
    {
        while(!Q.empty()) Q.pop();
        memset(vis,0,sizeof(vis));
        vis[n] = 1;
        node t;
        t.x = n, t.y = 0;
        Q.push(t);
		BFS();
    }
    return 0;
}


posted @ 2017-07-19 22:54  Sizaif  阅读(123)  评论(0编辑  收藏  举报