Catch that Cow
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.
1#include <cstdio>2#include <queue>3#include <cstring>4 using namespacestd;5 6 Const intmaxn=200050;7 intn,k;8 intVIS[MAXN];9 Ten struct Point One { A intPos; - intStep; - }; the - intBFS () - { -Queue<point>Q; + Point init; -init.pos=N; +init.step=0; A Q.push (init); atvis[n]=1; - while(!q.empty ()) - { -Point node=Q.front (); - Q.pop (); - if(node.pos==K) in returnNode.step; - Point newnode1,newnode2,newnode3; tonewnode1.pos=node.pos-1; +newnode2.pos=node.pos+1; -newnode3.pos=node.pos*2; thenewnode1.step=newnode3.step=newnode2.step=node.step+1; * if(!Vis[newnode1.pos]) $ {Panax Notoginsengvis[newnode1.pos]=1; - Q.push (newnode1); the } + if(!Vis[newnode2.pos]) A { thevis[newnode2.pos]=1; + Q.push (newnode2); - } $ if(newnode3.pos<maxn&&newnode3.pos>=0) $ if(!Vis[newnode3.pos]) - { -vis[newnode3.pos]=1; the Q.push (NEWNODE3); - }Wuyi } the } - Wu intMain () - { About while(SCANF ("%d%d", &n,&k)! =EOF) $ { -memset (Vis,0,sizeof(Vis)); - if(n>K) -printf"%d\n", N-K); A Else + { the intans=BFS (); -printf"%d\n", ans); $ } the } the return 0; the}
POJ 3275 Catch that Cow (BFS)