这个 D 好难,比 E 难多了(确信。
我们发现两种操作是一对相反的操作,类似加法和减法的关系。或者更直白地说,如果 通过其中一种操作变成了 ,那 也能通过另一种操作变回 。
然后你再考虑题目要求的从 变成 ,我们可以把任何变化的过程概括为,不断变小再不断变大的一个过程。
我们让 和 不断除以 (并向下取整),每次让两者中较大的去除,记录步数,直到 停止。此时当前步数次一定能把 变为 ,因为先让 除到 的值,然后再不断乘上去直到变成 ,恰好用了这么多步。
不难证明这个一定是最优的。于是就做完啦。
code && submission
#include<bits/stdc++.h>
#define LL long long
#define UInt unsigned int
#define ULL unsigned long long
#define LD long double
#define pii pair<int,int>
#define pLL pair<LL,LL>
#define pDD pair<LD,LD>
#define fr first
#define se second
#define pb push_back
#define isr insert
#define _i128 __int128
using namespace std;
LL T,x,y,k,cnt;
LL read(){
LL su=0,pp=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')pp=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){su=su*10+ch-'0';ch=getchar();}
return su*pp;
}
int main(){
T=read();
while(T--){
x=read(),y=read(),k=read();
cnt=0;
while(x!=y){
if(x<y)swap(x,y);
x/=k,cnt++;
}
cout<<cnt<<"\n";
}
return 0;
}如果本篇题解对你有帮助的话,麻烦你点一个小小的赞,真是太感谢啦!