Catch That Cow

题目:

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?

intput

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

题意:

给你两个地址a,b,求从a到b的最小步数,其中有三种走法,在现在的地址上往前走一步+1,在现在的地址上后退一步-1,又或者在现在的地址跳跃到你现在地址的2倍。

思路:

我刚开始想的是dfs,后来因为是求最小值,就还是用了bfs,这里有一些点需要注意一下,首先你得知道它的行走路径,就是那三种方法。然后就是它需要分情况讨论,因为它给的a可能大于b,也可能小于b。当a大于b时,它只能往后退才能到b处。最后就是可能会超时,我做了几次都是超时,后面把它不符合条件的continue,然后就A了;

#include<iostream>
#include<stdio.h>
#include<queue>
#include<algorithm>
#include<string.h>
#include<cmath>
#define maxn 100010
using namespace std;
struct node
{
    int x,num;
};
int n,k;
node start,nextt;
int vis[maxn];
void bfs()
{
    memset(vis,0,sizeof(vis));
    vis[n]=1;
    queue<node>q;
    start.x=n;
    start.num=0;
    q.push(start);
    while(!q.empty())
    {
        start=q.front();
        q.pop();
       for(int i=0;i<3;i++)
       {
           nextt=start;
            if(i==0)
                nextt.x=start.x*2;
            else if(i==1)
                nextt.x=start.x+1;
            else
                nextt.x=start.x-1;
            if(nextt.x<0||nextt.x>100000)//判断不符合条件的就不继续,减少时间;
                continue;
            if(!vis[nextt.x])
            {
                nextt.num+=1;
                vis[nextt.x]=1;
                q.push(nextt);
            }
            if(nextt.x==k)
            {
                cout<<nextt.num<<endl;
                return;
            }
        }
    }
}
int main()
{
    while(cin>>n>>k)
    {
        if(k<=n)    //如果k<=n,就只能往后退
            cout<<n-k<<endl;
        else       //但是k>n时,三种走法都是可以的
            bfs();
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值