Catch that cow(POJ_3278)

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

Hint

The fastest way for Farmer John to reach the fugitive cow is to move along the following path: 5-10-9-18-17, which takes 4 minutes.

这是第二次做这题,先后经历了MLE,RE,WA也是醉,分别来分析一下原因。MLE是因为一开始没想办法优化,写了一个最直接的bfs,然后就爆了。。。然后加了一个flag数组标记了已经走过的点,然后RE,一开始还以为是数组开小了之类的,后来仔细想了一下,是-1步的时候有可能会变成负数,当然RE。。。再次修改之后WA,发现是n==k的时候的情况结果不对。。。最终终于AC了,真艰辛。。这就是很久不刷题的后果么。。。QAQ

代码

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>

using namespace std;

struct node
{
    int num;
    int cnt;
};

bool flag[5001000]={0};

void bfs(int n,int k,int &ans)
{
    struct node a;
    a.num=n;
    a.cnt=0;
    queue<node>q;
    q.push(a);
    while(q.size())
    {
        struct node qq=q.front();
        flag[qq.num]=1;
        q.pop();
        if(qq.num+1==k||qq.num-1==k||qq.num*2==k)
        {
            ans=qq.cnt+1;
            return ;
        }
        struct node x;
        x.cnt=qq.cnt+1;
        x.num=qq.num+1;
        if(!flag[x.num])
            q.push(x);
        x.num=qq.num-1;
        if(x.num>=0&&!flag[x.num])
            q.push(x);
        x.num=qq.num*2;
        if(!flag[x.num]&&qq.num<k)
            q.push(x);
    }
}

int main()
{
    int n,k,ans=0;
    scanf("%d%d",&n,&k);
    if(n==k)
    {
        printf("0\n");
        return 0;
    }
    bfs(n,k,ans);
    printf("%d\n",ans);
    return 0;
}

你可能感兴趣的:(Catch that cow(POJ_3278))