Catch that cow
Time limit:2000 ms |
|
Memory limit:65536 K |
Total submissions:36079 |
|
Accepted:11123 |
Description
Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a pointN(0 ≤N≤ 100,000) on a number line and the cow is at a pointK(0
≤K≤ 100,000) on the same number line. Farmer John has two modes of transportation: Walking and teleporting.
* Walking: FJ can move from any pointXTo the pointsX-1 orX+ 1 in a single minute
* Teleporting: FJ can move from any pointXTo the point 2 ×XIn 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 way for Farmer John to reach the fugitive cow is to move along the following path: 5-10-9-18-17, which takes 4 minutes.
It is completely BFs, and there is no skill. It is mainly marked with visit to prevent re-search.
# Include <iostream> # include <stdio. h ># include <cstring> using namespace STD; struct tree {int X; int step;} queue [800050]; int visit [100050]; int N, K; int BFS () {int T, W, temp, Minx = 10000000, xx; t = W = 1; queue [T]. X = N; visit [N] = 1; queue [T]. step = 0; while (T <= W) {xx = queue [T]. x; If (XX> K) {temp = queue [T]. step + XX-K; // if it is greater than the result, it can only be reduced, so you can find it directly! If (temp <Minx) Minx = temp; t ++; // The T here must be added; otherwise, the error "continue ;} if (XX * 2 <= 100000 &&(! Visit [2 * XX]) {queue [++ w]. X = XX * 2; visit [2 * XX] = 1; // use visit to mark and prevent researching queue [w]. step = queue [T]. step + 1; if (queue [w]. X = k) {If (queue [w]. step <Minx) return queue [w]. step; else return Minx ;}}if (xx + 1 <= 100000 &&(! Visit [xx + 1]) {queue [++ w]. X = xx + 1; visit [xx + 1] = 1; queue [w]. step = queue [T]. step + 1; if (queue [w]. X = k) {If (queue [w]. step <Minx) return queue [w]. step; else return Minx ;}}if (XX >=1 &&(! Visit [xx-1]) {queue [+ + W]. X = xx-1; visit [xx-1] = 1; queue [w]. step = queue [T]. step + 1; if (queue [w]. X = k) {If (queue [w]. step <Minx) return queue [w]. step; else return Minx ;}t ++ ;}return-1 ;}int main () {While (scanf ("% d", & N, & K )! = EOF) {memset (visit, 0, sizeof (visit); If (n> = k) printf ("% d \ n", n-k ); elseprintf ("% d \ n", BFs ();} return 0 ;}