题解:ABC465 - D
题面:X to Y。
解题思路
题目中对 的变换描述为:当 或 时,可以将 变为 。这是一个可逆转的操作,于是可以想到建无向图求最短路。
分析一下建的这个图。首先把条件转化为 或 ,由此很容易发现这是一个根为 的 叉树,所求即为点 到点 的距离,可以使用 LCA,即 到 的距离加上 到 的距离。
具体步骤
-
求点 和点 的深度;
-
对齐深度(一格一格地向上跳);
-
同时往上跳(一格一格地向上跳)直到找到 并累加答案;
-
输出答案。
代码实现
#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;
}