搜索 G - 农民追牛问题(bfs)

本文介绍了一个有趣的追击问题,通过使用广度优先搜索算法来解决。该问题涉及一位农民追赶一只静止不动的逃逸奶牛,利用步行和瞬间传送两种方式,在一条数值线上寻找最佳路径。文章提供了完整的C++实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

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 pointsX - 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?

Sample Input

5 17

Sample Output

4

思路:
由题意 ,  特别明显的 , 用广度搜索来做 。
广度搜索: 1.将一个数压进栈去,取出栈首的元素,进行拓展(向前走一步,向后走一步,走到2*n的地方)
         2.将拓展的元素压进栈里 , 同时 将首元素 删除 。
         3.一直进行1,2 一直到搜索到为止。
Code:
#if 0
#include<iostream>
#include<queue>
using namespace std;
queue <int> q;
const int MAX = 100005 ;
int ret[MAX];
bool pd[MAX];
int bfs(int m,int k)
{
    if(m==k)return 0;      //别忘记 这种情况
    q.push(m);
    int cur;
    while(!q.empty())
    {
        cur=q.front();           //取出
        q.pop();                 //删除
        if(cur+1<MAX&&!pd[cur+1])  //进行拓展
        {
            q.push(cur+1);
            ret[cur+1]=ret[cur]+1;
            pd[cur+1]=true;
        }
        if(cur+1==k)break;
        if(cur-1>=0&&!pd[cur-1])
        {
            q.push(cur-1);
            ret[cur-1]=ret[cur]+1;
            pd[cur-1]=true;
        }
        if(cur-1==k)break;
        if(cur*2<MAX&&!pd[cur*2])
        {
            q.push(cur*2);
            ret[cur*2]=ret[cur]+1;
            pd[cur*2]=true;
        }
        if(cur*2==k) break;
    }
    return ret[k];
}
int main()
{ 
    int M , K ;
    cin>>M>>K;
    cout<<bfs(M,K)<<endl;
    return 0;
}


#endif 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值