제출 #12121

#제출 시각아이디문제언어결과실행 시간메모리
12121kriiiMin-cost GCD (GA9_mcg)C++14
41 / 100
110 ms32768 KiB
#include <stdio.h>
#include <algorithm>
#include <map>
using namespace std;

long long a,b,p,q,l;
int t;
std::map<int, long long> chk[100000];

long long go(long long a, long long b)
{
	if (a == 0 || b == 0) return 0;
	if (a == b) return p < q ? p : q;
	unsigned int h = a*b+a*3+b;
	long long &r = chk[t][h];
	if (r) return r;
	r = p + go(b,a%b);
	if (a > b){
		long long d = a / b, e = q * d;
		if (d <= l) r = min(r, e+go(a-b*d,b));
	}
	else{
		long long d = b / a, e = q * d;
		if (d <= l) r = min(r, e+go(a,b-a*d));
	}
	return r;
}

int main()
{
	int T; scanf ("%d",&T); while (T--){
		scanf ("%lld %lld %lld %lld",&a,&b,&p,&q);
		l = 1e18 / q;
		printf ("%lld\n",go(a,b));
		t++;
	}

	return 0;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...