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 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 17
Sample 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.
题意是:
给定一个起点,有三种方法能到达终点,分别是:
1.每次减 1 2.每次加 1 3. 每次以乘 2 前进
求最少的步数(用广搜 队列的方法)
分为两种情况:
一个是 n>=k 就只能以第一种的方法向后退,最少步数就是两数的 差
另一种是 n>=k 的情况
定义一个数组用于标记经过的位置坐标是否被访问过 就是 代码中的 flag 函数
满足范围即入队列,对当前的坐标进行标记,步数加1;
代码如下:

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<math.h>
#include<queue>
#include<algorithm>
using namespace std;
int flag[100002];
queue<int>q;
int BFS(int n,int k)
{
    int i,m,date,d;
    q.push(n);//满足条件的入队列
    flag[n]=1;
    while(!q.empty())//一定要判断 队列是否是空队列
    {
        date=q.front();
        q.pop();
        for(i=0;i<=2;i++)
        {
            if(i==0)
                d=date-1;//对应的三种情况
            if(i==1)
                d=date+1;
            if(i==2)
                d=date*2;
            if(d>=0&&d<100001&&flag[d]==0){//flag[d]==0 代表的是没有被访问过
                q.push(d);//入队列
                flag[d]=flag[date]+1;// 进行到该点的时候 是第几步
                if(d==k)
                    return flag[d]-1;/一开始定义的是 1,所以要减去 1
            }
        }
    }
}
int main()
{
    int n,k;
    while(~scanf("%d %d",&n,&k))
    {
        memset(flag,0,sizeof(flag));
        if(n>=k)
            printf("%d\n",n-k);
        else
            printf("%d\n",BFS(n,k));//去调用 广搜函数
    }
}

猜你喜欢

转载自blog.csdn.net/jkdd123456/article/details/80113621