Catch That Cow

来源:互联网 发布:阿里云大厦 部门 编辑:程序博客网 时间:2024/06/05 20:59

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 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 orX + 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 andK
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

你在N这个点,要到K这个点,N是可以+1,-1,*2,每次需要1个单位时间,请问到达K所需的时间。广搜一维的搜索,枚举三个变化,且走过的点要标记,无需再走。

#include<iostream>#include<cstdio>#include<queue>#include<cstring>using namespace std;struct node{int place;int time;}D,d;int n,k;int vis[100005];int main(){ scanf("%d%d",&n,&k); memset(vis,0,sizeof(vis)); queue<node>q;//开了个队列 while(!q.empty()){    q.pop(); }//用之前把队列清空 D.place = n; D.time = 0; q.push(D); vis[D.place]=1;//先把起点入队列while(!q.empty()){    D = q.front();    q.pop();//读出数据不要忘记将其剔除    if(D.place == k){        printf("%d\n",D.time);//如果搜到终点,就输出此时的时间        break;    }   for(int i = 0; i < 3; i ++){     if(i ==0)//枚举三种情况     d.place = D.place+1;     else if(i == 1)    d.place = D.place*2;    else     d.place = D.place-1;     d.time = D.time+1;     if(d.place < 0 || d.place >100000 || vis[d.place] == 1)//判断即将到的点有没有超界和被走过        continue;     q.push(d);//如果符合条件,就入队列     vis[d.place] = 1;//入队列的点都要标记       }}}


0 0