Catch that cow
Time limit:2000 ms |
|
Memory limit:65536 K |
Total submissions:44613 |
|
Accepted:13946 |
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
There is a farmer and a ox. They are on a digital axis. The Ox remains unchanged at K position, and the farmer starts at N position. Set the current farmer in M location, there are three options for each move: 1. Move to M-1; 2. Move to m + 1 location; 3. Move to M * 2 location. Ask the minimum number of moves that can be made to the place where the ox is located. Therefore, you can use BFs to search for these three statuses until you find the position of the ox.
# Include <cstdio> # include <iostream> # include <cstring> # include <queue> # include <algorithm> using namespace STD; const int n = 200100; int N, K; struct node {int X, step ;}; queue <node> q; int vist [N]; void BFS () {int cow, ans; while (! Q. empty () {node TMP = Q. front (); q. pop (); cow = TMP. x; ans = TMP. step; If (COW = k) {printf ("% d \ n", ANS); return;} If (COW> = 1 &&! Vist [cow-1]) // It must be meaningful after the value is reduced by 1, So cow> = 1 minus 1 {node temp; vist [cow-1] = 1; temp. X = cow-1; temp. step = ans + 1; q. push (temp);} If (COW <= K &&! Vist [cow + 1]) // Add 1 to {node temp; vist [cow + 1] = 1; temp. X = cow + 1; temp. step = ans + 1; q. push (temp);} If (COW <= K &&! Vist [Cow * 2]) // In the case of multiplication 2 {node temp; vist [Cow * 2] = 1; temp. X = 2 * cow; temp. step = ans + 1; q. push (temp) ;}} int main () {While (~ Scanf ("% d", & N, & K) {While (! Q. empty () Q. pop (); memset (vist, 0, sizeof (vist); vist [N] = 1; node T; T. X = N, T. step = 0; q. push (t); BFS ();} return 0 ;}