[AcWing 1100] 抓住那头牛

image

带条件的 BFS 最短路


点击查看代码
#include<bits/stdc++.h>

using namespace std;

typedef long long LL;

const int N = 2e5 + 10;

int n, m;
int d[N];

int bfs(int x)
{
    queue<int> q;
    q.push(x);
    memset(d, -1, sizeof d);
    d[x] = 0;
    while (q.size()) {
        auto t = q.front();
        q.pop();
        if (t + 1 <= m && d[t + 1] == -1) {
            d[t + 1] = d[t] + 1;
            q.push(t + 1);
        }
        if (t - 1 >= 0 && d[t - 1] == -1) {
            d[t - 1] = d[t] + 1;
            q.push(t - 1);
        }
        if (t * 2 < N && d[t * 2] == -1) {
            d[t * 2] = d[t] + 1;
            q.push(t * 2);
        }
        if (d[m] != -1)
            return d[m];
    }
    return -1;
}

void solve()
{
    cin >> n >> m;
    cout << bfs(n) << endl;
}

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);

    solve();

    return 0;
}

  1. 对于一个数 \(t\),能走到的数包括三种情况:
    \(t + 1 \leqslant k\),当 \(t + 1 > k\) 时,每走一个 \((t + 1)\),就一定要走一个 \((t - 1)\),一定不是最短路
    \(t - 1 \geqslant 0\),当 \(t - 1 < 0\) 时,每走一个 \((t - 1)\),就一定要走一个 \((t + 1)\),一定不是最短路
    \(2 \cdot t \leqslant MAX\),这里的 \(MAX\) 设置为 \(2 \times 10^{5}\),因为 \(k\) 最大为 \(10^{5}\)\(\times 2\) 这个操作最多到 \(2 \times 10^{5}\)
posted @ 2022-08-02 19:24  wKingYu  阅读(21)  评论(0)    收藏  举报