Catch that Cow
Time Limit: 2000MS |
|
Memory Limit: 65536K |
Total Submissions: 52537 |
|
Accepted: 16471 |
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 in a single minute
* TELEPORTING:FJ can move from any point x to the point 2x x 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:
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-Farmer John to reach the fugitive cow are to move along the following PATH:5-10-9-18-17, which takes 4 Minutes.
Source
Usaco Open Silver
AC Code
#include <stdio.h> #include <string.h> #include <queue> #include <iostream> #define INF 0xfffffff#define min (A, b) (a>b?b:a) using namespace std;struct s{int pos,step;} A,temp;int n,k,ans,vis[100100];void BFs () {memset (vis,0,sizeof (Vis)); A.pos=n;a.step=0;queue<struct s>q; Q.push (a); Vis[a.pos]=1;while (!q.empty ()) {A=q.front (); Q.pop (); for (int i=0;i<3;i++) {if (i==0) temp.pos=a.pos+1; if (i==1) temp.pos=a.pos-1;if (i==2) temp.pos=a.pos*2;temp.step=a.step+1;if (temp.pos==k) {ans=min (ans,temp.step); Continue;} if (temp.pos<0| | temp.pos>100001) continue;if (!vis[temp.pos]) {Vis[temp.pos]=1;q.push (temp);}}} int main () {while (scanf ("%d%d", &n,&k)!=eof) {ans=inf;if (n==k) {printf ("0\n"); continue;} if (n>k) {printf ("%d\n", n-k); continue;} BFS ();p rintf ("%d\n", ans);}}
POJ topic catch that Cow (BFS)