제출 #12158

#제출 시각아이디문제언어결과실행 시간메모리
12158xhaeMin-cost GCD (GA9_mcg)C++14
41 / 100
1000 ms1896 KiB
#include <unordered_set>
#include <unordered_map>
#include <cstdio>
#include <algorithm>
#include <cstring>

using namespace std;

long long dp[200][200];

long long a, b, p, q;
const long long INF = 1000000ll * 1000000ll * 500000ll;

unordered_set<long long> nodes;
unordered_map<long long, int> hash_;

void preproc(long long a, long long b)
{
	nodes.insert(a);
	nodes.insert(b);
	if(a == 0 || b == 0) return;
	preproc(b, a % b);
}

long long getAns(long long a, long long b)
{
	if(a == 0 || b == 0) return 0;

	int i1 = hash_[a], i2 = hash_[b];
	long long &ret = dp[i1][i2];
	if(ret != -1) return ret;
	
	ret = p + getAns(b, a % b);

	if(a >= b)
	{
		long long howMany = a / b;
		if(howMany <= ret / (double)q)
		{
			long long cand = howMany * q + getAns(a % b, b);
			ret = min(cand, ret);
		}
	}
	else
	{
		long long howMany = b / a;
		if(howMany <= ret / (double)q)
		{
			long long cand = howMany * q + getAns(a, b % a);
			ret = min(cand, ret);
		}
	}

	return ret;
}

int main(void)
{
	int T;
	scanf("%d", &T);
	while(T--)
	{
		scanf("%lld %lld %lld %lld", &a, &b, &p, &q);
		nodes.clear();
		preproc(a, b);
		int ind = 0;
		hash_.clear();
		for(auto v: nodes) hash_[v] = ind++;

		memset(dp, -1, sizeof(dp));
		printf("%lld\n", getAns(a, b));
	}

	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...