Final Boss: Team Selection Under GCD Constraint (H + J truly combined)

VERY HARD · C · 5000ms

As the true final boss of the problem set, Wasif fuses the two hardest ideas from the actual contest into one: choose exactly K players whose rating GCD is divisible by G, and among those, maximize the pairwise rating-difference sum. Read N player ratings. Answer Q queries, each giving (K, G): among all subsequences of EXACTLY K players (not necessarily increasing this time — any subsequence by original order/index) whose GCD of ratings is a multiple of G, find the maximum possible sum of pairwise |rating differences|. Print -1 if no valid subsequence of size K with GCD divisible by G exists. This genuinely fuses the two hardest ideas from your real contest (H's extremal pairwise-difference technique and J's divisor-based subsequence selection) into one problem — expect this to take real design effort, not just recall of a known template.

Input

Line1: N. Line2: N integers. Line3: Q. Next Q lines: K G.

Output

Q lines: the maximum sum, or -1.

Constraints

1 ≤ N, Q ≤ 2000, 1 ≤ a_i ≤ 2000

Sample Input

5
4 8 6 12 3
2
3 2
2 5

Sample Output

24
-1
main.c
Loading editor…

Write C, then Run (custom I/O) or Submit (sample tests). ⌘/Ctrl+Enter submits.

Final Boss: Team Selection Under GCD Constraint (H + J truly combined) · DIU ContestHub