题目链接:点击打开链接
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
#include<iostream>
#include<queue>
#include<string.h>
using namespace std;
#define INF 0x3f3f3f3f
struct node
{
int data;
int step;
} now,next;
int n,k;
int vis[100100];
queue<struct node>q;
int bfs()
{
while(!q.empty())
{
q.pop();
}
now.data=n;
now.step=0;
vis[now.data]=1;
q.push(now);
while(!q.empty())
{
now=q.front();
q.pop();
//next=now;
for(int i=0; i<3; i++)
{
if(i==0)
{
next.data=now.data-1;
}
if(i==1)
{
next.data=now.data+1;
}
if(i==2)
{
next.data=now.data*2;
}
next.step=now.step+1;
if(next.data==k)return next.step;
if(next.data<0||next.data>100000)continue;
if(vis[next.data]==0)
{
q.push(next);
vis[next.data]=1;
}
}
}
return INF;
}
int main()
{
while(cin>>n>>k)
{
memset(vis,0,sizeof(vis));
if(n<k)
{
cout<<bfs()<<endl;
}
else if(n==k)
{
cout<<"0"<<endl;
}
else cout<<n-k<<endl;
}
return 0;
}