Description
Farmer John had 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 are at a point K (0≤ K ≤100,000) on the same number line. Farmer John has 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 2x 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:
Nand
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-Farmer John to reach the fugitive cow are to move along the following PATH:5-10-9-18-17, which takes 4 Minutes.
#include"Cstdio"#include"Queue"#include"CString"using namespaceStd;typedef pair<int,int>P;Const intmaxn=100005;intVIS[MAXN];intn,k;intBFs () {Queue<P>que; Vis[n]=1; Que.push (P (0, N)); while(!Que.empty ()) {P now=Que.front (); Que.pop (); if(now.second==k) {returnNow.first; } for(inti=-1; i<=1; i++) { intNext; if(i==0) next=now.second*2; ElseNext=now.second+i; if(next>=0&&next<=maxn&&!Vis[next])//note conditions can not be less, and the order cannot be reversed {Vis[next]=1; Que.push (P (Now.first+1, next)); } } } return-1;}intMain () { while(SCANF ("%d%d", &n,&k)! =EOF) {memset (Vis,0,sizeof(VIS)); printf ("%d\n", BFS ()); } return 0;}
Virtual judge (feature a simple search C)