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.
题目大意 :一头牛从牛栏跑了出来,现在要把它抓回来,给你人的位置和牛的位置,人有三种移动方式,一种是当前坐标减一,一种是当前坐标加一,还有一种是当前坐标乘以二,三种移动方式耗费的时间是一样的,假设牛没有发现人要抓它,不移动,问要多长时间人抓到牛。
解题思路 :广搜,首先将人的位置加入队列,然后分三种情况进行判断。
#include<stdio.h>
#include<string.h>
int n,k;
int book[100100];
struct node
{
int x,s;
}que[100000],q;
int bfs()
{
int head,tail,i;
head = 0;
tail = 0;
que[tail].x = n;
que[tail].s = 0;
tail ++;
book[n] = 1;
if(n >= k)
return n-k;
while(head < tail)
{
q = que[head ++];
if(q.x+1 > 0&&q.x+1 < 100100&&book[q.x+1] == 0)
{
book[q.x+1] = 1;
que[tail].x = q.x + 1;
que[tail].s = q.s + 1;
tail ++;
if(q.x+1 == k)
return q.s + 1;
}
if(q.x-1 > 0&&q.x-1 < 100100&&book[q.x-1] == 0)
{
book[q.x-1] = 1;
que[tail].x = q.x - 1;
que[tail].s = q.s + 1;
tail ++;
if(q.x-1 == k)
return q.s + 1;
}
if(q.x*2 > 0&&q.x*2 < 100100&&book[q.x*2] == 0)
{
book[q.x*2] = 1;
que[tail].x = q.x*2;
que[tail].s = q.s + 1;
tail ++;
if(q.x*2 == k)
return q.s + 1;
}
}
}
int main()
{
int t;
while(~ scanf("%d %d",&n,&k))
{
memset(book,0,sizeof(book));
t = bfs();
printf("%d\n",t);
}
return 0;
}