Catch That Cow
(百练4001)
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.
Sample Input
5 17Sample 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.
代码:
#include<iostream> #include<cstdio> #include<queue> using namespace std; int ha[100010]={0};//标记走过的点 struct po//每个点的状态:位置,走到这个点的步数 { int x; int steps; po(int xx,int step):x(xx),steps(step){}//构造函数 }; void bfs(int n,int k); queue<po> q;//用来储存点的队列 int main(void) { int n,k; scanf("%d %d",&n,&k); bfs(n,k); return 0; } void bfs(int n,int k) { q.push(po(n,0));//把起点入队列 ha[n]=1; //并标记起点已经来过 while(!q.empty())//如果队列非空的话就继续扩展新的点 { po qi=q.front();//取出队列最前面的点(先进先出) q.pop();//弹出 if(qi.x==k)//如果到达目标 { printf("%d",qi.steps);//输出步数(一定是最短的) return; } //接下来是扩展在目前的位置经过一步所能到达的点 //可以把每一步的扩展写成一个结构体如: // struct // { // int x,y; // }dir[4]={{1,0},{0,1},{-1,0},{0,-1}}; if(qi.x-1>=0&&ha[qi.x-1]==0)//判断下一步的点有没有走过,并进行剪枝 //(判断如果进行下一步的话是否可能接近目标,或是永远都不能到达目标) { q.push(po(qi.x-1,qi.steps+1)); ha[qi.x-1]=1; } if(qi.x+1<=k&&ha[qi.x+1]==0) { q.push(po(qi.x+1,qi.steps+1)); ha[qi.x+1]=1; } if(qi.x<=k&&qi.x*2<=100000&&ha[qi.x*2]==0)//越界判断等 { q.push(po(qi.x*2,qi.steps+1)); ha[qi.x*2]=1; } } //如果队列为空时还没有到达目标则表明无解 return; } //bfs一般模版 //bfs() //{ // while(!q.empty()) // { // if()//到达目标 // { // // // break; // } // //扩展 // } // // //}