Catch That Cow(BFS和queue()用法)

来源:互联网 发布:淘宝上如何买衣服 编辑:程序博客网 时间:2024/06/15 16:28
Catch That Cow

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 - 1 or + 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 17

Sample Output

4

题意:

牛逃跑了,人要去抓回来这只牛,他们在一条直线上 ,现在牛的坐标是K,人的坐标是N,牛呆在原位置不动。人可移动X-1,X+1或2*X 的位置。每移动一步用一分钟,问人最少需要几分钟可以抓到牛。
思路:很明显的广搜题,有两种情况:一是牛在人的前面,即K<N,那么人只能一步一步的退着走,时间为N-K;第二种,牛在人的后面,那么人三种走法,这样搜下去即可,注意记录走过的坐标。 

代码如下:

#include<stdio.h>#include<string.h>#include<queue>#include<iostream>#define MAX 111111using namespace std;int vis[MAX];int f[MAX];int n,k;void BFS(){    vis[n]=1;    queue<int> q;    q.push(n);    while(!q.empty())    {        int x=q.front();        q.pop();        if(x==k) printf("%d\n",f[x]);        if(x-1>=0&&!vis[x-1])        {            vis[x-1]=1;            q.push(x-1);            f[x-1]=f[x]+1;        }        if(x+1<=MAX&&!vis[x+1])        {            vis[x+1]=1;            q.push(x+1);            f[x+1]=f[x]+1;        }        if(x*2<=MAX&&!vis[x*2])        {            vis[x*2]=1;            q.push(x*2);            f[x*2]=f[x]+1;        }    }}int main(){    while(~scanf("%d%d",&n,&k))    {        memset(vis,0,sizeof(vis));        memset(f,0,sizeof(f));        BFS();    }    return 0;}


0 0
原创粉丝点击