kuangbin带你飞系列----poj3278 Catch That Cow

本题题意:农夫和奶牛分别在数轴的两个点上,农夫可进行三种操作,将位置变为X+1,X-1,X*2,问最少几次操作后农夫能找到奶牛。

代码如下:

/*
    
    Title:poj3278

    Author:mtl6906
    
    时间复杂度:O(n);    

*/
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
queue<int> q;
int a[100001];
int n,k;
/*
    
    检查该步骤是否越界

*/
void check(int s,int t)
{
    if(t > 100000 || t < 0)return;
    if(a[t]==-1)
    {
        a[t] = a[s] + 1;
        q.push(t);
    }
}
/*
    
    三种操作

*/
void walk(int s)
{
    check(s,s+1);
    check(s,s-1);
    check(s,s<<1);
}
/*

    广度优先搜索,剪枝

*/
void bfs(int s)
{
    q.push(s);
    a[s] = 0;
    while(!q.empty())
    {
        walk(q.front());
        if(a[k]!=-1)return;
        q.pop();
    }
}
int main()
{
    while(scanf("%d%d",&n,&k)!=EOF)
    {
        memset(a,-1,sizeof(a));
        bfs(n);
        printf("%d\n",a[k]);
    }
    return 0;
}

这道题挺简单的,bfs搜索+dp优化。

posted @ 2017-09-06 19:55  mtl6906  阅读(171)  评论(0编辑  收藏  举报