- Total time limit:
- 2000ms
- Memory Limit:
- 65536kB
-
- Describe
-
-
The farmer knows the position of a bull and wants to catch it. Both the farmer and the ox are located on the axis, the farmer starts at point N (0<=n<=100000) and the ox is at point K (0<=k<=100000). Farmers have two ways of moving:
1. Move from X to X-1 or x+1, one minute per move 2, moving from X to 2*x, each move takes a minute Suppose the cow is not aware of the farmer's actions and stands still. How long does it take at least for the farmer to catch the bull?
-
- Input
-
- two integers, N and K
-
- Output
-
- an integer, the minimum number of minutes a farmer can take to catch a cow.
-
- Sample input
-
-
5 17
-
- Sample output
-
-
4
The ordinary BFS. Be careful to prune and open large arrays.
1#include <iostream>2#include <algorithm>3#include <cstdio>4#include <cmath>5 using namespacestd;6 intn,k;7 BOOLvis[300001];8 intpos[1000000];9 intstep[1000000];Ten voidBFS () { One intHd=0, tl=1; Apos[++hd]=N; -step[hd]=0; - while(hd<=TL) { the intnow=POS[HD]; - if(now==k) { -printf"%d\n", STEP[HD]); - return; + } - intnext=now*2; + if(next>=0&& next<=100000&&!Vis[next]) { Avis[next]=1; atpos[++tl]=Next; -step[tl]=step[hd]+1;} -next=now+1; - if(next<=100000&&!Vis[next]) { -pos[++tl]=Next; -vis[next]=1; instep[tl]=step[hd]+1;} -next=now-1; to if(next>=0&&!Vis[next]) { +vis[next]=1; -pos[++tl]=Next; thestep[tl]=step[hd]+1;} *hd++; $ }Panax Notoginseng } - intMain () { thescanf"%d%d",&n,&k); + BFS (); A return 0; the}
Openjudge 2971 grab the bull.