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.
大体的意思就是在一定范围内找一只不动的牛,每次有三种选择
1.加一 2.减一 3.乘二
每次选择消耗都为一
注意对路径进行优化
比如超出范围的不应入列
#include<queue>
#include<algorithm>
#include<cmath>
#include<string.h>
#include<algorithm>
#include<iostream>
using namespace std;
int n,k,a[10000],cnt,vis[1000000];
struct Node
{
int timme,t;
};
int bfs()
{
memset(vis,0,sizeof(vis));//不能少~~
queue<Node>q;
Node fis;
fis.timme=0;
fis.t=n;
vis[n]=1;
q.push(fis);
while(q.size())
{
Node cur=q.front();
q.pop();
if(cur.t==k) return cur.timme;
Node next;
for(int i=1;i<=3;i++)
{
if(i==1)
{
next.timme=cur.timme+1;
next.t=cur.t+1;
if(next.t>1e+5||next.t<0)//越界
continue;
if(vis[next.t])
continue;
vis[next.t]=1;
q.push(next);
}
if(i==2)
{
next.timme=cur.timme+1;
next.t=cur.t-1;
if(next.t<0||next.t>1e5) //越界
continue;
if(vis[next.t])//走过
continue;
vis[next.t]=1;
q.push(next);
}
if(i==3)
{
next.timme=cur.timme+1;
next.t=cur.t*2;
if(next.t>1e+5||next.t<0)//越界
continue;
if(vis[next.t])
continue;
vis[next.t]=1;
q.push(next);
}
}
}
}
int main()
{
scanf("%d %d",&n,&k);
if(n!=k)
{
bfs();
printf("%d\n",bfs());
}
else
{
printf("0\n");
}
return 0;
}