POJ 3278 Catch That Cow

 

Catch That Cow

Time Limit: 2000 ms Memory Limit: 65536 KiB

Problem Description

Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number line. Farmer John has two modes of transportation: walking and teleporting. * Walking: FJ can move from any point X to the points X - 1 or X + 1 in a single minute * Teleporting: FJ can move from any point X to the point 2 × X in a single minute. If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?

Input

Line 1: Two space-separated integers: N and K

Output

Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.

Sample Input

5 17

Sample Output

4

提示:如果你要做POJ的题,你要注意一点,当用C++的时候,不要用到bits/stdc++.h万能头文件,因为POJ判题中不存在此头文件,HDU部分判题也不包含此头文件
   此题主要就是用到广度遍历BFS,遍历能到达牛的位置的点

代码实现如下(g++):
# include <cstdio>
# include <string.h>
# include <queue>

using namespace std;

int n,m,ans;
int num[100010];
int main(void)
{
    while(~scanf("%d %d",&n,&m))
    {
        queue<int>t;
        t.push(n);
        num[n]=1;
        while(!t.empty())
        {
            int c=t.front();
            if(c==m)
            {
                ans=num[c];
                break;
            }
            t.pop();
            if(c-1>=0&&!num[c-1])//如果c-1没有被遍历过,将其入队
            {
                num[c-1]=num[c]+1;
                t.push(c-1);
            }
            if(c+1<=100000&&!num[c+1])//如果c+1没有被遍历过,将其入队
            {
                num[c+1]=num[c]+1;
                t.push(c+1);
            }
            if(c*2<=100000&&!num[c*2])//如果c*2没有被遍历过,将其入队
            {
                num[c*2]=num[c]+1;
                t.push(c*2);
            }
        }
        printf("%d
",ans-1);
    }
    return 0;
}


/***************************************************
Result: Accepted
Take time: 0ms
Take Memory: 892KB
****************************************************/
原文地址:https://www.cnblogs.com/jkxsz2333/p/9505583.html