前言
做完这个题可以看 Constructive ver.,题解。
题目分析
考虑通过方式。
若 ,不需要走。
考虑直接过,花费 。
设 为 的一个约数。
考虑 ,这样代价是 。
显然如果需要中间松弛一步,而且不是 的约数,那么去 中至少有一个需要额外代价。
如果松弛多步:显然第一步、最后一步最小是 ,中间的步都是多余的。
所以答案:若 ,是 ;否则是 。
代码
#include<bits/stdc++.h>
#define int long long
typedef __int128 i128;
using namespace std;
int q,x,y;
i128 ans;
i128 lcm(int a,int b){
return (i128)(a/__gcd(a,b))*b;
}
void output(i128 a){
static stack<char>st;
while(!st.empty())
st.pop();
do st.push((a%10)^48),a/=10;
while(a);
while(!st.empty())
putchar_unlocked(st.top()),st.pop();
putchar_unlocked('\n');
return;
}
signed main(){
for(cin>>q;q;--q){
cin>>x>>y;
ans=lcm(x,y);
if(x==y){
cout<<"0\n";
continue;
}
output(min(ans,(i128)(x+y)));
}
return 0;
}