Catch That Cow(广搜)

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.

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.

 

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define ull unsigned long long
#define ll long long


using namespace std;

int to[2]={1,-1};
int a,b,sum;
int vis[100000];
struct place
{
    int x,time;
};
int check(place k)
{
    if(k.x<0||k.x>100000||vis[k.x]==1)
        return 0;
    return 1;
}
int bfs(place n)
{
    place m,next;
    queuew;
    w.push(n);
    while(!w.empty())
    {
        m=w.front();//让m赋值为队列中的第一个元素
        w.pop();
        if(m.x==b)
            return m.time;
        for(int i=0;i<2;i++)
        {
            next.x=m.x+to[i];
            next.time=m.time+1;
            if(next.x==b)
                return next.time;
            if(check(next))
            {
                w.push(next);
                vis[next.x]=1;
            }
        }
        next.x=m.x*2;
        next.time=m.time+1;
        if(next.x==b)
            return next.time;
        if(check(next))
        {
            w.push(next);
            vis[next.x]=1;
        }
    }
    //return 0;
}
int main() {
    //int i, j, t;
    place x1;
    while (~scanf("%d %d", &a, &b)) {
        memset(vis, 0, sizeof(vis));
        x1.x = a;
        x1.time = 0;
        vis[x1.x] = 1;
        sum = 0;
        sum = bfs(x1);
        printf("%d\n", sum);
    }
    return 0;
}

 

你可能感兴趣的:(bfs&&dfs)