Catch That Cow
农夫知道一头牛的位置,想要抓住它。农夫和牛都于数轴上 ,农夫起始位于点 N(0<=N<=100000) ,牛位于点 K(0<=K<=100000) 。农夫有两种移动方式: 1、从 X移动到 X-1或X+1 ,每次移动花费一分钟 2、从 X移动到 2*X ,每次移动花费一分钟 假设牛没有意识到农夫的行动,站在原地不。最少要花多少时间才能抓住牛?
Input
一行: 以空格分隔的两个字母: N 和 K
(多组输入)
Output
一行: 农夫抓住牛需要的最少时间,单位分钟
Sample Input
5 17
Sample Output
4
Hint
农夫使用最短时间抓住牛的方案如下: 5-10-9-18-17, 需要4分钟.
#include<iostream>
#include<queue>
#include<string.h>
using namespace std;
const int M=200000+10;
int flag[M];
int n,m;
struct node{
int x,step;
friend bool operator < (node a,node b){//重载符
return a.step>b.step;
}
};
void BFS(int x1,int x2)
{
priority_queue<node>que;
node e1,e2;
memset(flag,0,sizeof(flag));
e1.x=x1, e1.step=0;
que.push(e1);
flag[e1.x]=1;
int ans=-1;
while(!que.empty()){
e1=que.top();
que.pop();
if(e1.x==x2){
ans=e1.step;
break;
}
int a=e1.x;
int p[3]={1,-1,a}; //位置增加a
for(int i=0;i<3;i++){
e2.x=e1.x+p[i];
if(flag[e2.x]==1) continue;
else if(e2.x<0||e2.x>100000) continue;
else e2.step=e1.step+1;
que.push(e2);
flag[e2.x]=1;
}
}
cout<<ans<<endl;
}
int main()
{
while(cin>>n>>m){
if(n>=m) cout<<n-m<<endl;
else BFS(n,m);
}
return 0;
}