Catch That Cow

                                   Catch That Cow

                                              Time Limit : 4000/2000ms (Java/Other)   Memory Limit : 131072/65536K (Java/Other)
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
 

题意:牛逃跑了,人要去抓回来这只牛,他们在一条直线上 ,现在牛的坐标是K,人的坐标是N,牛呆在原位置不动。人有两种行进方式,步行和传送,步行可以向前或向后走一步,传送为到达人当前坐标*2 的位置。每行进一次用一分钟,问人最少需要几分钟可以抓到牛。

思路:很明显的广搜题,有两种情况:一是牛在人的前面,即K<N,那么人只能一步一步的退着走,时间为N-K;第二种,牛在人的后面,那么人三种走法(把步行分为两种)都可以,这样搜下去即可,注意记录走过的坐标。

#include<iostream>
#include<cstring>
using namespace std;
int vis[100000];
int dis[100000];
int q[100000];
int n,k;
int bfs(int n)
{
    int rear=0,front=0,u;
    vis[n]=1;
    q[rear++]=n;
    while(front<rear)
    {
        u=q[front++];
        if(u==k)
            break;
        if(u*2<=100000 && vis[2*u]==0 && u*2 >0)    //判断是否满足条件和是否访问过
        {
            dis[u*2]=dis[u]+1;    //这一步的时间
            q[rear++]=u*2;        //加入队列
            vis[u*2]=1;           //记录访问过
        }
        if(u+1<=100000 && vis[u+1]==0 && u+1>0)
        {
            dis[u+1]=dis[u]+1;
            q[rear++]=u+1;
            vis[u+1]=1;
        }
        if(u-1<=100000 && u-1>0 && vis[u-1]==0)
        {
            dis[u-1]=dis[u]+1;
            q[rear++]=u-1;
            vis[u-1]=1;
        }
    }
    return 1;
}
int main()
{
    while(cin>>n>>k)
    {
        memset(vis,0,sizeof(vis));
        memset(q,0,sizeof(q));
        if(k<n)
        {
            cout<<n-k<<endl;
        }
        else
        {
            bfs(n);
            cout<<dis[k]<<endl;
        }
    }
    return 0;
}

 

posted on 2013-10-05 22:00  天梦Interact  阅读(267)  评论(0编辑  收藏  举报