Description

农夫知道一头牛的位置,想要抓住它。农夫和牛都于数轴上 ,农夫起始位于点 N(0<=N<=100000) ,牛位于点 K(0<=K<=100000) 。农夫有两种移动方式: 1、从 X移动到 X-1或X+1 ,每次移动花费一分钟 2、从 X移动到 2*X ,每次移动花费一分钟 假设牛没有意识到农夫的行动,站在原地不动。最少要花多少时间才能抓住牛?

Input

一行: 以空格分隔的两个字母: N 和 K

Output

一行: 农夫抓住牛需要的最少时间,单位分钟

Sample Input

5 17

Sample Output

4

Hint

农夫使用最短时间抓住牛的方案如下: 5-10-9-18-17, 需要4分钟.

 

解题思路:

1. 从起点x出发,初始操作次数step为0

2. 产生三种状态 x-1,x+1,x * 2,并放入队列, 同时操作次数 step + 1

3. 从队列中取出一个数,如果这个数不等于k,回到第二步

4. 否则找到正解,返回step

// #include <bits/stdc++.h>
#include <cstdio>
#include <cstring>
#include <queue>;
#include <algorithm>

using namespace std;
const int N = 100010;

int n, k;
int used[N];
int step[N];
queue<int> que;

int bfs()
{
    memset(used, 0, sizeof(used));
    memset(step, 0, sizeof(step));
    
    while(!que.empty()) que.pop();
    que.push(n);
    used[n] = 1;
    while(!que.empty())
    {
        int now = que.front();    que.pop();
        for(int i=0; i < 3; i++)
        {
            int next;
            if(i == 0)  next = now + 1;
            else if(i == 1) next = now - 1;
            else if(i == 2) next = now * 2;
            if(next < 0 || next > N)   continue;
            if(!used[next])
            {
                que.push(next);
                used[next] = 1;
                step[next] = step[now] + 1;
            }
            if(next == k)   return step[next];
        }
        
    }
}

int main()
{
    while(scanf("%d %d", &n, &k) != EOF)
    {
        if(n >= k)  printf("%d\n", n-k);
        else    printf("%d\n", bfs());
    }


    return 0;
}