poj3278 catch that cow

Catch That Cow
Time Limit: 2000MSMemory Limit: 65536K
Total Submissions: 43653Accepted: 13605

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
#include<stdio.h>
#include<string.h>
int front,rear,visit[100001],bu[100001],m,n;
typedef struct
{
	int w;
}sqtype;
sqtype sq[100001];
void bfs()
{
	int x;
	front=rear=0;
	sq[0].w=m;
	bu[m]=0;
	visit[m]=1;
	while(front<=rear)
	{
		x=sq[front].w;
		if(visit[n]!=0)
		break;
		if(x-1>=0&&visit[x-1]==0)
		{
			rear++;
			sq[rear].w=x-1;
			bu[x-1]=bu[x]+1;
			visit[x-1]=1;
		}
		if(x+1<=100001&&visit[x+1]==0)
		{
			rear++;
			sq[rear].w=x+1;
			bu[x+1]=bu[x]+1;
			visit[x+1]=1;
		}
			if(x*2<=100001&&visit[x*2]==0)
		{
			rear++;
			sq[rear].w=x*2;
			bu[x*2]=bu[x]+1;
			visit[x*2]=1;
		}
		front++;
	}
}
main()
{
	scanf("%d%d",&m,&n);
	memset(visit,0,sizeof(visit));
	bfs();
	printf("%d",bu[n]);
}
posted @ 2015-05-06 18:33  awenzero  阅读(92)  评论(0编辑  收藏  举报