Link: poke here
Catch that CowTime limit:2000ms Memory limit:65536k
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
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.
Test instructions
X axis The person is at position n where the ox is at position K, and the man walks to the cow at least how many steps it takes
There are three ways to walk: left, right, coordinate.
idea:How many steps does it take to keep the BFS at the current position?
Code:
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include < string> #include <vector> #include <ctime> #include <queue> #include <set> #include <map > #include <stack> #include <iomanip> #include <cmath> #define MST (SS,B) memset ((ss), (b), sizeof (SS )) #define MAXN 0x3f3f3f3f#define MAX 1000100///#pragma comment (linker, "/stack:102400000,102400000") typedef long LONG Ll;typedef unsigned long long ull; #define INF (1ll<<60) -1using namespace std;int vis[200100],n,k;struct node{int X,step; Node (int x=0,int step=0): X (x), step (step) {}};void BFS () {MST (vis,0); Queue<node> Qu; Qu.push (Node (n,0)); Vis[n]=1; while (!qu.empty ()) {node Now=qu.front (); Qu.pop (); if (!vis[now.x+1] && now.x+1<100001) {if (now.x+1==k) {cout<<now.step+1<<e Ndl return; } vis[now.x+1]=1; Qu.push (node(now.x+1,now.step+1)); } if (!vis[now.x-1] && now.x-1>=0) {if (now.x-1==k) {cout<<now.step+1 <<endl; return; } vis[now.x-1]=1; Qu.push (Node (now.x-1,now.step+1)); } if (!vis[now.x*2] && now.x*2<100001) {if (now.x*2==k) {cout<<now.step+1 <<endl; return; } vis[now.x*2]=1; Qu.push (Node (now.x*2,now.step+1)); }}}int Main () {while (scanf ("%d%d", &n,&k)!=eof) {if (n==k) cout<<0<<endl; else BFS (); } return 0;}
POJ 3278 BFS