SDUT_1028_Catch That Cow(bfs)

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

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.

Example Input

5 17

Example Output

4

題意:在一個數軸上,人在N位置,牛在K位置,人去找牛(人從 N到K),牛不動,人有兩種走法,一種是+1或-1,另一種是在x位置,直接跳到2*x位置。(說明x 到x+1,x-1,2*x是連通的)
示例是 : 5 17
可以 從5跳到10,再從10到9,從9跳到18,從18到17,走4步;
也可以 5->4,4->8,8->16,16->17 都是4 步,用的步數最少;
分析:
當人的位置小於牛的位置,即n < k 時,可以進行+ 、-、 * ,因爲通過這些都可以增大,而 n > k時只能進行 減 ,這樣才能找到牛。
當找到牛的時候,輸出所用的步數。

代碼

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int book[500005];

struct node
{
    int x;
    int s;
}que[500005];
int main()
{
    int n,k;
    int head = 1;
    int tail = 1;
    scanf("%d%d",&n,&k);

    que[head].x = que[tail].x = n;
    que[tail++].s = 0;
    book[n] = 1;
    while(head < tail)
    {
        int m = que[head].x;
        //找到牛
        if(m == k)
        {
            printf("%d\n",que[head].s);
            break;
        }
        //人的位置小於牛的
        if(m <= k&&book[m-1]==0)
        {
            book[m-1]=1;
            que[tail].x = m-1;
            que[tail++].s = que[head].s+1;
        }
        if(m <= k && book[m+1]==0)
        {
            book[m+1]=1;
            que[tail].x = m+1;
            que[tail++].s = que[head].s+1;
        }
        if(m <= k&&book[m*2]==0)
        {
            book[m*2] = 1;
            que[tail].x = m*2;
            que[tail++].s = que[head].s+1;
        }
        //人的位置大於牛
        if(m > k && book[m-1]==0)
        {
            book[m-1]=1;
            que[tail].x = m-1;
            que[tail++].s = que[head].s+1;
        }
        head ++ ;
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章