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(0±n=100000)处开始,在同一条线上,母牛处于点K(0±k±100000)。农民约翰有两种交通方式:步行和长途运输。
*行走:FJ可以从任意点X移动到点X - 1或X+ 1在一分钟内
*远程传送:FJ可以在一分钟内从任意点X移动到点2×X。
如果奶牛不知道它的追求,它根本不动,农民约翰需要多久才能取回它呢?
思路:
广搜,如果n>=k,就只能往回行走了,如果n<k,三种走法都可以,利用广搜把符合条件的位置,步数加入队列,并标记为走过了。每次从队首开始查找并更新队首,直到查找到牛的位置,输出步数。
不要忘记初始化标记的数组!
代码:
#include<stdio.h>
#include<string.h>
int book[100010];
struct data
{
int x;
int step;
}q[1000000],t;
int main()
{
int n,head,tail,k;
while(scanf("%d%d",&n,&k)!=EOF)
{
memset(book,0,sizeof(book));
if(n>=k)
printf("%d\n",n-k);
else
{
head=0;
tail=0;
book[n]=1;
q[tail].x=n;
q[tail].step=0;
tail++;
while(head<tail)
{
t=q[head++];
if(t.x+1>0&&t.x+1<100010&&book[t.x+1]==0)
{
q[tail].x=t.x+1;
q[tail].step=t.step+1;
tail++;
book[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&&book[t.x-1]==0)
{
q[tail].x=t.x-1;
q[tail].step=t.step+1;
tail++;
book[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&&book[t.x*2]==0)
{
q[tail].x=t.x*2;
q[tail].step=t.step+1;
tail++;
book[t.x*2]=1;
if(t.x*2==k)
{
printf("%d\n",t.step+1);
break;
}
}
}
}
}
return 0;
}
#include<stdio.h>
#include<string.h>
#include<queue>
#include<algorithm>
using namespace std;
struct note
{
int x;
int step;
};
int book[200010];
int main()
{
struct note A,B,next;
queue<note>que;
int a,b,k;
while(scanf("%d%d",&a,&b)!=EOF)
{
memset(book,0,sizeof(book));
while(!que.empty())
{
que.pop();
}
A.x=a;
A.step=0;
book[A.x]=1;
que.push(A);
while(!que.empty())
{
B=que.front();
if(B.x==b)
{
printf("%d\n",B.step);
break;
}
que.pop();
for(k=0;k<3;k++)
{
next=B;
if(k==0)
next.x=next.x+1;
if(k==1)
next.x=next.x-1;
if(k==2)
next.x=next.x*2;
next.step++;
if(next.x>=0&&next.x<=200000&&book[next.x]==0)
{
book[next.x]=1;
que.push(next);
}
}
}
}
return 0;
}