POJ3278 Catch That Cow 最少步数问题(BFS)

解析一道关于农夫在数轴上寻找静止不动的牛的算法题,使用BFS算法实现,考虑农夫的两种移动方式,寻找最短路径。

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

在这里插入图片描述
Description
农夫知道一头牛的位置,想要抓住它。农夫和牛都于数轴上 ,农夫起始位于点 N(0<=N<=100000) ,牛位于点 K(0<=K<=100000) 。农夫有两种移动方式: 1、从 X移动到 X-1或X+1 ,每次移动花费一分钟 2、从 X移动到 2*X ,每次移动花费一分钟 假设牛没有意识到农夫的行动,站在原地不动。最少要花多少时间才能抓住牛?

Input
一行: 以空格分隔的两个字母: N 和 K

Output
一行: 农夫抓住牛需要的最少时间,单位分钟

Sample Input
5 17

Sample Output
4

题目翻译摘自:https://blog.youkuaiyun.com/qq_40663503/article/details/98228452


BFS,还是注意要在入队的时候更新访问情况
每次循环结束要重置数组和队列
善用memset

    memset(walked, 0x3f, sizeof(walked));
    while(!queue.empty())
        queue.pop();

代码如下:

#include <cstdio>
#include <queue>
#include <cstring>

using namespace std;

int main() {

    int N,K=0;
    queue<pair<int,int> > queue;
    // 若数值*2大于15000,则肯定有更短的方式能够访问到,所以将数组大小定位150000多一点
    int walked[150005] ;
    while(scanf("%d %d",&N,&K)!=EOF)
    {
        if(K<N)
        {
            printf("%d\n",N-K);
            continue;
        }
        queue.push({N,0});
        walked[N]=1;
        while(!queue.empty())
        {
            pair<int,int> current = queue.front();
            queue.pop();
            if(current.first == K) {
                printf("%d\n",current.second);
                break;
            }
            for (int i = 0; i < 3; i++) {
                int nx;
                if (i == 0) nx = current.first - 1;
                else if (i == 1) nx = current.first + 1;
                else nx = 2 * current.first;
                // 注意判断条件
                if ((nx > 0 && nx < 2 * K && nx<150001) && walked[nx] == 0) {
                    queue.push({nx, current.second + 1});
                    walked[nx] = 1;
                }
            }
        }
        memset(walked, 0x3f, sizeof(walked));
        while(!queue.empty())
            queue.pop();
    }

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值