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

在这里插入图片描述
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.csdn.net/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;
}

发布了3 篇原创文章 · 获赞 0 · 访问量 20

猜你喜欢

转载自blog.csdn.net/weixin_43812215/article/details/104520002
今日推荐