思路
这道题对于每一次的x,我们都能做出乘k+x或是除以k的选择,我们可以将其视为一个决策树,乘k加x为其子节点,除k为其父节点,这样这道题就是求出x和y的lca了。
tip:遇到决策尝试转化成决策树。
正解
cpp
#include<bits/stdc++.h>
#define int long long
using namespace std;
int T;
inline void solve(){
int x, y, k;
cin>>x>>y>>k;
int ans = 0;
while(x != y) {
if(x > y) x /= k;
else if(x < y) y /= k;
ans ++;
}
cout<<ans<<'\n';
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(0);
cin>>T;
while(T--) solve();
return 0;
}