POJ-3278-Catch That Cow

版权声明:转载请注明出处 https://blog.csdn.net/doubleguy/article/details/82050156

农夫知道一头牛的位置,想要抓住它。农夫和牛都于数轴上 ,农夫起始位于点 N(0<=N<=100000) ,牛位于点 K(0<=K<=100000) 。农夫有两种移动方式: 1、从 X移动到 X-1或X+1 ,每次移动花费一分钟 2、从 X移动到 2*X ,每次移动花费一分钟 假设牛没有意识到农夫的行动,站在原地不。最少要花多少时间才能抓住牛?

Input

一行: 以空格分隔的两个字母: N 和 K

Output

一行: 农夫抓住牛需要的最少时间,单位分钟

Sample Input

5 17

Sample Output

4

Hint

农夫使用最短时间抓住牛的方案如下: 5-10-9-18-17, 需要4分钟.

对于每一个节点(假设任意节点为a),他的子节点有3种情况,2×a,a+1,a-1.然后从起点开始搜直到找到结果。

AC代码如下:

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
const int maxn = 1e5+10;
int vis[maxn];
struct node
{
    int x;
    int step;
    friend bool operator < (node a,node b)
    {
        return a.step>b.step;
    }
};

void bfs(int stn,int edk)
{
    int ans=0;
    priority_queue<node>q;
    node now,next;
    now.x=stn;
    vis[stn]=1;
    now.step=0;
    q.push(now);
    while(!q.empty())
    {
        now=q.top();
        q.pop();
        if(now.x==edk)
        {
            ans=now.step;
            break;
        }
        for(int i=0;i<3;i++)
        {
            if(i==0)
                next.x=now.x*2;
            else if(i==1)
                next.x=now.x+1;
            else
                next.x=now.x-1;
            next.step=now.step;
            if(next.x>=0&&next.x<=1e5&&!vis[next.x])
            {
                vis[next.x]=1;
                next.step++;
                q.push(next);
            }
        }
    }
    printf("%d\n",ans);
}

int main()
{
    int n,k;
    scanf("%d%d",&n,&k);
    bfs(n,k);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/doubleguy/article/details/82050156