FJUT ACM 1276 Catch That Cow

Catch That Cow

TimeLimit: 2000ms  MemoryLimit:65536KB
64-bit integer IO format:%lld
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 - 1 or + 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.
 
SampleInput
5 17
SampleOutput
4
[思路]:这题就是个bfs,很水的bfs
因为他是一维的,
所以只要考虑+1,-1,*2这三种情况
还有如果n>k那么就只能倒退
输出n-k就ojbk了
贴上代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#define MAXN 200005
using namespace std;
int vids[MAXN];
int step[MAXN];
queue<int>q;
int bfs(int n,int k)
{
    int head,ends;
    q.push(n);
    while(!q.empty())
    {
        head=q.front();
        q.pop();
        for(int i=0; i<3; i++)
        {
            if(i==0)
                ends=head-1;
            if(i==1)
                ends=head+1;
            if(i==2)
                ends=head*2;
            if(ends<0||ends>MAXN)continue;
            if(vids[ends]==0)
            {
                q.push(ends);
                vids[ends]=1;
                step[ends]=step[head]+1;
            }
            if(ends==k)
            {
                return step[ends];
            }
        }
    }

}
int main()
{
    int n,k;
    int sum;
    while(~scanf("%d%d",&n,&k))
    {
        memset(step,0,sizeof(step));
        memset(vids,0,sizeof(vids));
        if(n>=k)printf("%d
",n-k);
        else
        {
            sum=bfs(n,k);
            printf("%d
",sum);
            while(!q.empty())
                q.pop();
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/qq136155330/p/8494333.html