Catch That Cow
Problem 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 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
题意描述:
把一个数变成另一个数,可以通过加1或减1或者变成现在数的2倍,求最少的步数
程序代码:
#include<stdio.h>
#include<string.h>
#include<queue>
#include<algorithm>
using namespace std;
struct data{
int x;
int y;
int step;
};
int book[200010];
int main()
{
int a,b,k;
struct data A,B,next;
queue<data>que;
while(scanf("%d%d",&a,&b)!=EOF)
{
while (!que.empty())
{
que.pop();
}
A.x=a;
A.step=0;
memset(book,0,sizeof(book));
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;
}