제출 #20136

#제출 시각아이디문제언어결과실행 시간메모리
20136hongjun7Min-cost GCD (GA9_mcg)C++14
57 / 100
1000 ms1212 KiB
#include <cstdio>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
typedef long long ll;
ll a, b, p, q;
map <pair<ll, ll>, ll> d;
ll f(ll x, ll y) {
	if (x == 0 || y == 0) return 0;
	if (d.count({ x, y })) return d[{x, y}];
	ll d1 = f(y, x%y) + p, d2 = 1e18;
	if (x >= y) {
		if ((x / y) <= d1 / q) d2 = f(x % y, y) + (x / y)*q;
	}
	else {
		if ((y / x) <= d1 / q) d2 = f(x, y % x) + (y / x)*q;
	}
	if (d1 > d2) d1 = d2;
	d[{x, y}] = d1;
	return d1;
}
int main() {
	int T;
	for (scanf("%d", &T); T--; ) {
		scanf("%lld%lld%lld%lld", &a, &b, &p, &q);
		d.clear();
		printf("%lld\n", f(a, b));
	}
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...