I - 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 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?


输入

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

输出

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

样例输入

5 17

样例输出

4

提示

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.

一维的bfs,但是需要注意输入的n<K时,直接输出k-n,就不用用bfs耗时了;
还有就是当走到 比k的时候就不能往前走了,这里要做剪枝处理;
代码如下,仅供参考:

#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <stack>
#include <queue>
#include <string.h>
#include <vector>
#include <queue>
#include <cmath>
#include <iomanip>
using namespace std;

int n,k;
int dx[2]={1,-1};
int vis[200050];

struct node
{
    int x;int step;
    node(int a,int b)
    {
        x=a;step=b;
    }
};


int bfs()
{
    queue<node> que;
    node no(n,-1);
    que.push(no);vis[n]=1;
    while(!que.empty())
    {

        node cur=que.front();
        que.pop();

        for(int i=0;i<3;i++)
        {
            int xx=cur.x;
            if(i==2)
            {
                xx*=2;
                if(xx>k*2)continue;
                if(cur.x==k)return cur.step+1;
                if(!vis[xx])
                {
                    node no2(xx,cur.step+1);
                    vis[xx]=1;
                    que.push(no2);
                }
            }
            else
            {
                xx+=dx[i];
                if(xx>k*2)continue;
                if(cur.x==k)return cur.step+1;
                if(xx<0||vis[xx])
                    continue;

                else
                {
                    vis[xx]=1;
                    node no2(xx,cur.step+1);
                    que.push(no2);
                }
            }
        }
    }
    return -1;
}

int main()
{
    while(cin>>n>>k)
    {
        memset(vis,0,sizeof(vis));
        if(n>k)
            cout<<n-k<<endl;
        else
        cout<<bfs()<<endl;
    }
}


你可能感兴趣的:(I - Catch That Cow)