POJ 4001:抓住那头牛

描述

农夫知道一头牛的位置,想要抓住它。农夫和牛都位于数轴上,农夫起始位于点N(0<=N<=100000),牛位于点K(0<=K<=100000)。农夫有两种移动方式:

1、从X移动到X-1或X+1,每次移动花费一分钟

2、从X移动到2*X,每次移动花费一分钟

假设牛没有意识到农夫的行动,站在原地不动。农夫最少要花多少时间才能抓住牛?

输入

两个整数,N和K

输出

一个整数,农夫抓到牛所要花费的最小分钟数

样例输入

5 17

样例输出

4
这道题一开始想的是用深搜的方式,但深搜应该会爆,因为最大的位置在100000处。 

由于每次移动的代价是相同的,都是耗时一分钟,所以宽搜应该是正确的解法,就类似墨水染色的方法。
#include<iostream>
#include<queue>
using namespace std;

typedef pair<int,int> PII;
int st[100010];

int main(){
    int n,k,idx = 0;
    cin>>n>>k;
    queue<PII> q;
    q.push({n,idx});
    while(q.size()){
        PII t = q.front();
        q.pop();
        if (st[t.first]) continue;
        if (t.first == k){
            cout<<t.second<<endl;
            return 0;
        }
        int index = t.first;
        st[index] = 1;
        if (index + 1 <= 100000)
            q.push({index + 1,t.second + 1});
        if (index - 1 >= 0)
            q.push({index - 1,t.second + 1});
        if (index * 2 <= 100000 && index >= 0)
            q.push({index * 2,t.second + 1});
    }
    
    return 0;
}
发布了341 篇原创文章 · 获赞 32 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_41514525/article/details/102764193
今日推荐