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
Output
Sample Input
5 17
Sample Output
4
Hint
这是一个广搜+队列的问题,很复杂的问题用这些方法就能很轻松的写出来。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
#include<iostream>
#include<queue>
#include<stdio.h>
#include<string.h>
using namespace std;
queue<int> q;
int step[100001],visit[100001];
int main()
{
int a,b;
while(scanf("%d %d",&a,&b)!=EOF)
{
memset(visit,0,sizeof(visit));
if(a>=b)
printf("%d\n",a-b);
else
{
int t,temp;
queue<int>q;
q.push(a); // 插入队列
visit[a]=1;
while(!q.empty())
{
t=q.front();//队列首元素
q.pop(); //出队列
for(int i=0; i<3; i++)
{
if(i==0)
temp=t+1;
else if(i==1)
temp=t-1;
else
temp=t*2;
if(temp>100000||temp<0)
continue;
if(visit[temp]==0)
{
step[temp]=step[t]+1;
if(temp==b)
printf("%d\n",step[temp]);
visit[temp]=1;
q.push(temp);
}
}
}
}
}
return 0;
}