# | 제출 시각 | 아이디 | 문제 | 언어 | 결과 | 실행 시간 | 메모리 |
---|---|---|---|---|---|---|---|
12688 | gs14004 | Min-cost GCD (GA9_mcg) | C++98 | 0 ms | 0 KiB |
이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
using namespace std;
typedef long long lint;
lint dp[100], dp2[100];
lint pow[19] = {1,0};
lint a,b,p,q;
inline bool calc_valid(lint x, lint y){
int t = lower_bound(pow,pow+19,x) - pow + lower_bound(pow,pow+19,y) - pow;
return t < 18;
}
lint f(lint x, lint y, int step){
if(x == 0 || y == 0) return 0;
if(x >= y){
if(~dp[step]) return dp[step];
if(!calc_valid(q,x/y)) return dp[step] = f(y,x%y,step+1) + p;
else return dp[step] = min(f(y,x%y,step+1) + p,f(x%y,y,step+1) + q*(x/y));
}
else{
if(~dp2[step]) return dp2[step];
if(!calc_valid(q,y/x)) return 5e18;
else return dp2[step] = f(x,y%x,step+1) + q * (y/x);
}
}
void solve(){
memset(dp,-1,sizeof(dp));
memset(dp2,-1,sizeof(dp2));
scanf("%lld %lld %lld %lld",&a,&b,&p,&q);
if(a < b) printf("%lld\n",min(p + f(b,a,0),f(a,b,0)));
else printf("%lld\n",f(a,b,0));
}
int main(){
for(int i=1; i<=18; i++) pow[i] = pow[i-1] * 10;
int t;
scanf("%d",&t);
while (t--) {
solve();
}
}