Catch That Cow

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.

 

 

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.

题意描述:

在一条数轴直线上一个农夫从n位置去寻找k位置的牛,农夫一次可以位置+1,-1或*2,求农夫找到牛的最小步数。

解题思路:

当n>=k是农夫只能向后走,所以最小步数为n-k。当n<k时农夫三种走法都可以,利用广搜将每次符合条件步数加入队列,同时将位置标记为已走过;每次从队首开始查找并更新队首,直到查找到牛的位置,输出步数。

#include<stdio.h>
#include<string.h>
int a[100010];
struct A
{
	int x;
	int step;
}q[1000000],t;
int main()
{
	int n,k,head,tail;
	while(scanf("%d%d",&n,&k)!=EOF)
	{
		memset(a,0,sizeof(a));
		if(n>=k)
			printf("%d\n",n-k);
		else
		{
			head=0;
			tail=0;
			a[n]=1;
			q[tail].x=n;
			q[tail].step=0;//将起点加入队列 
			tail++;//队列扩展,等待下次使用 

			while(head<tail)
			{
				t=q[head++];//将队首赋给t从队首开始查找,并释放,更新队首 
				//判断三种走发,若符合条件 ,加入队列步数加一同时扩展队列等待下次使用;若到达位置输出步数跳出循环 
				if(t.x+1>0&&t.x+1<100010&&a[t.x+1]==0) 
				{
					q[tail].x=t.x+1;
					q[tail].step=t.step+1;
					tail++;
					a[t.x+1]=1;
					if(t.x+1==k)
					{
						printf("%d\n",t.step+1);
						break;
					}
				}
				if(t.x-1>0&&t.x-1<100010&&a[t.x-1]==0)
				{
					q[tail].x=t.x-1;
					q[tail].step=t.step+1;
					tail++;
					a[t.x-1]=1;
					if(t.x-1==k)
					{
						printf("%d\n",t.step+1);
						break;
					}
				}
				if(t.x*2>0&&t.x*2<100010&&a[t.x*2]==0)
				{
					q[tail].x=t.x*2;
					q[tail].step=t.step+1;
					tail++;
					a[t.x*2]=1;
					if(t.x*2==k)
					{
						printf("%d\n",t.step+1);
						break;
					}
				}
			}
		}
	}
	return 0;
}