This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#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)*q < d1) d2 = f(x % y, y) + (x / y)*q;
}
else {
if ((y / x)*q < d1) 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 time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |