C - Catch That Cow
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
题目大意
在一条笔直的道路上,农民要捉牛,给出农民和牛的位置,牛不动,农民有三种方式可以走,例如农民在5,牛在17. 农民可以倍数级走,5*2。可以向前走一步5+1, 向后走一步5-1,每一种方式都花费一分钟,问最少花费的时间可以捉到牛。
思路
这是一道典型的广搜题,核心是使用一个结构体,有两个变量,分别保存其坐标和时间
这里需要注意的是,当n>=k时,只能向左走时间耗费才最少,当n<k时则需要添加到队列里求其最小值
#include<stdio.h>
int next[3]={-1,1,2};
int book[100005]={0};
struct Que
{
int x;
int len;
};
int main()
{
int n,k;
int head=0,rear=0;
struct Que que[100005];
scanf("%d%d",&n,&k);
if(n >= k) { printf("%d\n",n-k); return 0;} //直接得出值
que[head].x = n;
que[head].len = 0;
rear++;
while(head < rear)
{
struct Que t = que[head++];//出队列和赋值
for(int i = 0;i < 3;++i)
{
int t1;
if(i == 2) t1=t.x*next[i];
else t1 = t.x+next[i];
if(t1 < 0 || t1 > 100000) continue; //判断出界,n<=100000
if(!book[t1])
{
book[t1] = 1;
que[rear].x = t1;
que[rear++].len=t.len+1;
}
if(t1 == k) //找到目标位置
{
printf("%d\n",que[rear-1].len); return 0;
}
}
}
return 0;
}