题解:【ABC465】D - X to Y

· · 题解

题解:ABC465 - D

题面:X to Y。

解题思路

题目中对 x 的变换描述为:当 \lfloor \frac{x}{K} \rfloor = y 或 \lfloor \frac{y}{K} \rfloor = x 时,可以将 x 变为 y。这是一个可逆转的操作,于是可以想到建无向图求最短路。

分析一下建的这个图。首先把条件转化为 y = \lfloor \frac{x}{K} \rfloor 或 y \in [x K, xK + K - 1],由此很容易发现这是一个根为 0 的 K 叉树,所求即为点 X 到点 Y 的距离,可以使用 LCA,即 X 到 \text{LCA}(X, Y) 的距离加上 \text{LCA}(X, Y) 到 Y 的距离。

具体步骤

  1. 求点 X 和点 Y 的深度;

  2. 对齐深度(一格一格地向上跳);

  3. 同时往上跳(一格一格地向上跳)直到找到 \text{LCA}(X, Y) 并累加答案;

  4. 输出答案。

代码实现

#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
#include <atcoder/all>
#define endl '\n'
using namespace std;
typedef long long ll;

inline int dep(ll x, ll k) {
    int res = 0;
    while (x > 0) {
        x /= k, res++;
    }
    return res;
}

int main(int argc, char* argv[]) {
    // freopen(".in", "r", stdin);
    // freopen(".out", "w", stdout);
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr); cout.tie(nullptr);

    int times;
    cin >> times;
    while (times--) {
        ll x, y, k;
        cin >> x >> y >> k;
        // 求深度
        int dx = dep(x, k), dy = dep(y, k);
        ll ans = 0;
        // 对齐深度
        while (dx > dy) {
            x /= k, dx--, ans++;
        }
        while (dy > dx) {
            y /= k, dy--, ans++;
        }
        // 同时往上跳
        while (x != y) {
            x /= k, y /= k;
            ans += 2;
        }
        cout << ans << endl;
    }
    return 0;
}