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
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
bool used[1000001];//记录经过的点,bool的头文件为string
int vis[1000001];//记录时间
int bfs(int s,int e)//s为起点,e为终点
{
queue<int> q;//头文件为queue
int pos=s;
used[pos]=true;
vis[pos]=0;//起始时时间为零
q.push(pos);//队列初始化
while(!q.empty())
{
pos=q.front();//检索队首元素
q.pop();//出栈
if(pos==e) return vis[pos];//特殊情况当起点就是终点时,返回0
if(pos+1<=100000&&!used[pos+1])//判断是否可执行
{
used[pos+1]=true;//没走过的点就赋为一
vis[pos+1]=vis[pos]+1;
q.push(pos+1);//探索完后入栈
}
if(pos-1>0&&!used[pos-1])
{
used[pos-1]=true;
vis[pos-1]=vis[pos]+1;
q.push(pos-1);
}
if(pos*2<=100000&&!used[pos*2])
{
used[pos*2]=true;
vis[pos*2]=vis[pos]+1;
q.push(pos*2);
}
}
return 0;
}
int main()
{
int i,j;
while(scanf("%d%d",&i,&j)!=EOF)//输入多组数据
{
memset(used,false,sizeof(used));//清零
cout<<bfs(i,j)<<endl;
}
return 0;
}