SDUT_1028_Catch That Cow(bfs)

来源:互联网 发布:杭州seo公司哪家好 编辑:程序博客网 时间:2024/06/01 21:03

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;}