HLG 1012 Catch That Cow 【广搜】

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 pointXto the pointsX- 1 orX+ 1 in a single minute
* Teleporting: FJ can move from any pointXto the point 2 ×Xin 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

For each test case :

Line 1: Two space-separated integers:NandK

Process to the end of file.

Output

For each test case :

Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.

Sample Input

5 17
100 100
Sample Output
4
0
 
代码:
View Code
#include<stdio.h>
#include<string.h>
int used[100001];
int a[100001];
int step[100001];
int main()
{

int n,m,i,u,front,rear;
while(scanf("%d%d",&n,&m)!=EOF)
{
memset(used,0,sizeof(used));
front=0;rear=-1;
a[++rear]=n;
used[n]=1;
step[n]=0;
while(front<=rear)
{
u=a[front++];
if(u!=m)
{
if(u-1>=0&&used[u-1]==0)
{a[++rear]=u-1;step[u-1]=step[u]+1;used[u-1]=1;}
if(u+1<=100000&&used[u+1]==0)
{a[++rear]=u+1;step[u+1]=step[u]+1;used[u+1]=1;}
if(2*u<=100000&&used[2*u]==0)
{a[++rear]=2*u;step[2*u]=step[u]+1;used[2*u]=1;}
}
else break;
}
printf("%d\n",step[u]);
}
return 0;
}

posted @ 2012-03-15 12:35  'wind  阅读(182)  评论(0编辑  收藏  举报