Catch That Cow

Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 49787 Accepted: 15623

Description

Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a pointN (0 ≤N ≤ 100,000) on a number line and the cow is at a pointK (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 pointsX- 1 orX+ 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 andK

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.

Source


题目链接:http://poj.org/problem?id=3278


题目大意:一条线上,给一个起点和一个终点,有三种走法,走一次1秒,位置坐标加1,减1和乘2,求从起点到终点的最短时间


题目分析:裸BFS,有可能n >= k,这时候只需要求n-k即可,n < k时,搜一搜就行了,千万注意!!虽然肯定有解,但是在BFS函数最后还是要return一个值,不然会wa


#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
int n, k;
bool vis[200005];

struct Node
{
    int num;
    int step;
};

int BFS()
{
    memset(vis, false, sizeof(vis));
    queue <Node> q;
    Node st, cur, t;
    st.num = n;
    st.step = 0;
    vis[n] = true;
    q.push(st);
    while(!q.empty())
    {
        t = q.front();
        cur = t;
        q.pop();
        if(t.num == k)
            return t.step;
        if(t.num + 1 < 200001 && !vis[t.num + 1])
        {
            vis[t.num + 1] = true;
            t.num ++;
            t.step ++;
            q.push(t);
        }
        t = cur;
        if(t.num - 1 >= 0 && !vis[t.num - 1])
        {
            vis[t.num - 1] = true;
            t.num --;
            t.step ++;
            q.push(t);
        }
        t = cur;
        if(t.num * 2 < 200001 && !vis[t.num * 2])
        {
            vis[t.num * 2] = true;
            t.num *= 2;
            t.step ++;
            q.push(t);
        }
    }
    return 0;
}

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


Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐