Catch that Cow
Time Limit: 2000MS Memory Limit:32768KB 64bit IO Format:%i64d &%i64u
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 inch a single minute
* TELEPORTING:FJ can move from any point X to the point 2xX 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:n and 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
AnalysisFrom one point to another, there are several ways to go in each step, which is typical of the BFS problem.
Tips
- Note that the array is not large enough to open
- At each beginning to determine whether the solution has been searched
1#include <stdio.h>2#include <string.h>3#include <queue>4 5 using namespacestd;6 7 intvis[120000];8 intN,k,flag;9 Ten structNode One { A intx; - intTM; - }root; the - voidBFS () - { -memset (Vis,0,sizeof(Vis)); +Queue<node>que; - Que.push (root); + AVis[root.x] =1; at intans=100005; - - while(!que.empty ()) - { -Node q =Que.front (); - Que.pop (); in - //printf ("q.x =%d\n", q.x); to + if(q.x = =k) - { theAns =Q.tm; *Flag =1; $ Break;Panax Notoginseng } - the Node q1,q2,q3; + A if(q.x+1<100005&&!vis[q.x +1] ) the { + //printf ("q2.x =%d\n", q.x+1); -q2.x = q.x +1; $Q2.tm = Q.tm +1; $ -vis[q2.x] =1; - Que.push (q2); the } - Wuyi if(q.x-1>=0&&!vis[q.x-1] ) the { - //printf ("q1.x =%d\n", q.x-1); Wuq1.x = q.x-1; -Q1.tm = Q.tm +1; About $vis[q1.x] =1; - Que.push (Q1); - } - A + the if(q.x *2<100005&&!vis[q.x *2] ) - { $ //printf ("q3.x =%d\n", q.x*2); theq3.x = q.x *2; theQ3.tm = Q.tm +1; the thevis[q3.x] =1; - Que.push (Q3); in the } the } About if(flag) printf ("%d\n", ans); the //Else printf (" -1\n"); the } the + - intMain () the {Bayi the while(~SCANF ("%d%d",&n,&k)) the { -Flag =0; - theRoot.x =N; theRoot.tm =0; the the BFS (); - } the the return 0; the}
HDU2717 Catch that Cow (BFS)