农夫知道一头牛的位置,想要抓住它。农夫和牛都于数轴上 ,农夫起始位于点 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分钟.
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 52 53 54 | #include<iostream> #include<cstring> #include<queue> #include<algorithm> #include<cstdio> using namespace std; struct node { int x; int step; friend bool operator < (node a,node b){ return a.step>b.step; } }; const int MAXN=1e5+5; int vis[MAXN]; void BFS(int sx,int ex) { priority_queue<node> que; memset(vis,1,sizeof(vis)); node e1,e2; e1.x=sx;e1.step=0; vis[sx]=0; que.push(e1); int res=-1; while(que.size()){ e1=que.top();que.pop(); if(e1.x==ex){ res=e1.step; break; } for(int i=0;i<3;i++){ if(i==0)e2.x=e1.x-1; if(i==1)e2.x=e1.x+1; if(i==2)e2.x=e1.x*2; if(e2.x<0||e2.x>100000)continue; if(vis[e2.x]==0)continue; e2.step=e1.step+1; vis[e2.x]=0; que.push(e2); } } printf("%d\n",res); } int main() { int n,k; scanf("%d%d",&n,&k); if(n>=k)printf("%d\n",n-k); else BFS(n,k); return 0; } |