搜索 G题

来源:互联网 发布:购网络机顶盒 编辑:程序博客网 时间:2024/06/05 08:09

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.
2.解题思路:

    这道题的题意为给你两个位置,求第一个位置到第二个位置的最小步数(可以前走一步,后走一步,或向前走该位置数的两倍)。

     该题为BFS题,用队列储存每次三种走法的位置,然后从队头挨着搜,直到走到要求到的位置结束。

3.代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <queue>
using namespace std;
const int MAX = 100002;
int n,k,ans;
int a[MAX];
queue<int> q;
bool yes(int x)
{
    if(x>=0 && x<=k+2 && a[x]==-1)
    return true;
    return false;
}
int bfs(int x)
{
    q.push(x);
    a[x] = 0;
    while(!q.empty())
    {
        x = q.front();
        q.pop();
        if(x==k)
        break;
        if(yes(x+1))
        {
            a[x+1] = a[x] + 1;
            q.push(x+1);
        }
        if(yes(x-1))
        {
            a[x-1] = a[x] + 1;
            q.push(x-1);
        }
        if(yes(x*2))
        {
            a[2*x] = a[x] + 1;
            q.push(2*x);
        }
    }
    return a[k];
}


int main()
{


    while(cin>>n>>k&&n!=-1)
    {
        if(n>=k)
        {
            cout<<n-k;
            continue;
        }
        while(!q.empty())
        {
            q.pop();
        }
        ans = INT_MAX;
        memset(a,-1,sizeof(a));
        ans = bfs(n);
        cout<<ans;
    }
    return 0;
}