Pay q per subtraction step and p per modulo step to reduce the pair (a, b) until one entry is zero, and report the cheapest total cost.
Medium7GreedyNumber theoryMathNo attempts yetTime limit1sMemory limit32 MBComputing the greatest common divisor of two natural numbers comes up often. In this problem you compute it at a smaller cost.
Seokhwan and Sangsu are natural number processors. A customer hands them one ordered pair of natural numbers, and they process the pair and hand it back.
For example:
Seunghyun has an ordered pair of natural numbers (a,b). He is good at mathematics, and he worked out that sending the pair to Seokhwan and Sangsu in a suitable order eventually reaches a pair with ab=0. At that point a+b is the greatest common divisor of the two numbers he started with.
Seunghyun then wondered what the smallest cost of reaching ab=0 is once a, b, p, and q are fixed. He cannot change the numbers himself, so he can only request processing. Compute that smallest cost for him.
The first line contains the number of test cases T.
Each of the next T lines contains one test case. Line i (1≤i≤T) contains four natural numbers ai, bi, pi, qi separated by spaces.
For each test case, print the smallest cost in won on its own line. Seunghyun starts from the pair (ai,bi), pays pi won for one request to Seokhwan and qi won for one request to Sangsu, and has to reach aibi=0 using processing requests only.
When (a,b,p,q) is (7,3,1,1), (8,3,1,1), or (7,3,3,2), using Seokhwan alone is optimal.
When it is (55,34,10,9), both of them are needed. In the path below, --q--> is a request to Sangsu and --p--> is a request to Seokhwan.
(55, 34) --q--> (21, 34) --q--> (21, 13) --q--> (8, 13) --q--> (8, 5)
(8, 5) --p--> (5, 3) --q--> (2, 3) --q--> (2, 1) --p--> (1, 0)
Six requests to Sangsu and two to Seokhwan cost 6×9+2×10=74 won.