1426:Find The Multiple

1426:Find The Multiple

题解

3种情况每次尝试即可,注意尝试的时候需要判断一下范围,会更快,在x*2的情况下,如果不判断可能会越界。

#include <iostream>
#include <queue>
using namespace std;
int main()
{
    
    
    int N, M;
    cin >> N >> M;

    //  当前的位置 已走步数
    queue<pair<int, int>> q;
    q.push({
    
    N, 0});

    // 每条路只走一次即可
    bool dp[200005] = {
    
    0};
    dp[N] = 1;
    while (!q.empty())
    {
    
    
        auto x = q.front();
        q.pop();
        if (x.first == M)
        {
    
    
            cout << x.second << endl;
            return 0;
        }

        if (x.first - 1 >= 0 && dp[x.first - 1] == 0)
            q.push({
    
    x.first - 1, x.second + 1}), dp[x.first - 1] = 1;

        if (dp[x.first + 1] == 0)
            q.push({
    
    x.first + 1, x.second + 1}), dp[x.first + 1] = 1;
        // 不加 会越界
        if (x.first < M && dp[x.first * 2] == 0)
            q.push({
    
    x.first * 2, x.second + 1}), dp[x.first * 2] = 1;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_45653525/article/details/113067048
今日推荐