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 <stdio.h>
#include <algorithm>
#include <vector>
using namespace std;
long long a,b,p,q,l;
vector<pair<long long, long long> > u;
void gcd(long long a, long long b)
{
if (a == 0 || b == 0);
else if(a > b) gcd(b,a%b);
else gcd(a,b%a);
if (a < b) swap(a,b);
u.push_back(make_pair(a,b));
if (a != b) u.push_back(make_pair(b,a));
}
int find(vector<pair<long long, long long> > &e, int i, pair<long long, long long> p)
{
while (i--) if (e[i] == p) return i;
return -1;
}
int main()
{
int T; scanf ("%d",&T); while (T--){
scanf ("%lld %lld %lld %lld",&a,&b,&p,&q);
u.clear(); l = 1e18 / q;
gcd(a,b);
vector<long long> d(u.size());
for (int i=0;i<u.size();i++){
if (u[i].first == 0 || u[i].second == 0) d[i] = 0;
else if (u[i].first == u[i].second) d[i] = p < q ? p : q;
else{
long long na = u[i].first, nb = u[i].second;
d[i] = p + d[find(u,i,make_pair(nb,na%nb))];
if (na > nb){
long long nd = na / nb, ne = q * nd;
if (nd <= l) d[i] = min(d[i], ne+d[find(u,i,make_pair(na-nb*nd,nb))]);
}
else{
long long nd = nb / na, ne = q * nd;
if (nd <= l) d[i] = min(d[i], ne+d[find(u,i,make_pair(na,nb-na*nd))]);
}
}
}
printf ("%lld\n",d[find(u,u.size(),make_pair(a,b))]);
}
return 0;
}
# | 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... |