Catch That Cow
Time Limit: 2000MS
Memory Limit: 65536KB
Problem Description
Farmer John has 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 is at a point K (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 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 2 × 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: N and K
Output
Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.
Example Input
5 17
Example Output
4
题意大概就是:约翰丢了一头牛,这头牛和约翰在同一个数轴上,数轴大于0。约翰有两种交通方式,要么步行,一次最多只能前进一步或者退后一步;要么传送,只能传送为当前位置的2倍。给你约翰和牛的位置,问你约翰最少通过几次能找到牛?牛沉浸在自由的喜悦中浑然不知约翰在找她,随所以牛静止不动。
显然BFS,层数最少使得n==k
#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 vis[N]; void BFS() { //搜索关于X的三种状态 int X, STEP; while(!Q.empty()) //队列非空 { node t = Q.front(); //队头元素t出队 Q.pop(); X = t.x; STEP = t.step; if(X == k) //如果当前位置和目的位置相等 直接输出step { printf("%d\n",STEP); return ; } if(X >= 1 && vis[X - 1]==0) //要保证减1后有意义,所以要X >= 1,并且X-1未被访问 { node temp; vis[X - 1] = 1; //访问置1 temp.x = X - 1; //当前位置 temp.step = STEP + 1; //步数加1 Q.push(temp); //进队 } if(X <= k && vis[X + 1]==0) //要保证减1后有意义当前位置比目的地小并未被访问 { node temp; vis[X + 1] = 1; temp.x = X + 1; temp.step = STEP + 1; Q.push(temp); //进队 } if(X <= k && vis[X * 2]==0) //要保证*2后有意义且未被访问 { node temp; vis[X * 2] = 1; temp.x = 2 * X; temp.step = STEP + 1; Q.push(temp); //入队 } } } int main() { while(~scanf("%d%d",&n,&k)) { while(!Q.empty()) //依次弹出 Q.pop(); memset(vis,0,sizeof(vis)); vis[n] = 1; // node t; t.x = n, t.step = 0; //n是当前位置,step是走的步数 Q.push(t); //t进队 BFS(); } return 0; }