EPIC Institute of Technology Round August 2024 (Div. 1 + Div. 2)
F2
Court Blue (Hard Version)
Codeforces
2800
原题
← F1G →
翻译中…

This is the hard version of the problem. In this version, it is not guaranteed that $n=m$, and the time limit is higher. You can make hacks only if both versions of the problem are solved.

翻译中…

In the court of the Blue King, Lelle and Flamm are having a performance match. The match consists of several rounds. In each round, either Lelle or Flamm wins.

翻译中…

Let $W_L$ and $W_F$ denote the number of wins of Lelle and Flamm, respectively. The Blue King considers a match to be successful if and only if:

翻译中…
  • after every round, $\gcd(W_L,W_F)\le 1$;
  • at the end of the match, $W_L\le n, W_F\le m$.
翻译中…

Note that $\gcd(0,x)=\gcd(x,0)=x$ for every non-negative integer $x$.

翻译中…

Lelle and Flamm can decide to stop the match whenever they want, and the final score of the performance is $l \cdot W_L + f \cdot W_F$.

翻译中…

Please help Lelle and Flamm coordinate their wins and losses such that the performance is successful, and the total score of the performance is maximized.

翻译中…

Input

翻译中…

The first line contains an integer $t$ ($1\leq t \leq 10^3$) — the number of test cases.

翻译中…

The only line of each test case contains four integers $n$, $m$, $l$, $f$ ($2\leq n\leq m \leq 2\cdot 10^7$, $1\leq l,f \leq 10^9$): $n$, $m$ give the upper bound on the number of Lelle and Flamm's wins, $l$ and $f$ determine the final score of the performance.

翻译中…

Unusual additional constraint: it is guaranteed that, for each test, there are no pairs of test cases with the same pair of $n$, $m$.

翻译中…

Output

翻译中…

For each test case, output a single integer — the maximum total score of a successful performance.

翻译中…

Note

翻译中…

In the first test case, a possible performance is as follows:

翻译中…
  • Flamm wins, $\gcd(0,1)=1$.
  • Lelle wins, $\gcd(1,1)=1$.
  • Flamm wins, $\gcd(1,2)=1$.
  • Flamm wins, $\gcd(1,3)=1$.
  • Flamm wins, $\gcd(1,4)=1$.
  • Lelle and Flamm agree to stop the match.
翻译中…

The final score is $1\cdot2+4\cdot5=22$.

翻译中…

样例

Input #1
8
3 4 2 5
4 4 1 4
6 6 2 2
7 9 2 3
8 9 9 1
2 7 1 4
5 9 1 4
5 6 6 7
Output #1
22
17
18
37
77
30
41
59
InputCopy OutputCopy
Input #2
2
3082823 20000000 1341 331
20000000 20000000 3 5
Output #2
10754065643
159999991
InputCopy OutputCopy
Input #3
1
139 1293 193 412
Output #3
559543
InputCopy OutputCopy
题目信息
题号
2002F2
时间限制
4 s
内存限制
512 MB
标签
暴力
动态规划
数学
数论

题面与样例版权归 Codeforces 及出题人所有;中文翻译由 AI 生成(CI 管线),如有出入请以原文为准。