#P17167. [CEOI 2026] Towers

[CEOI 2026] Towers

Problem Description

You have nn computers and mm towers all at distinct positions along a line. You need to pair computers using cables in such a way that every cable starts at some computer, visits some towers and ends at another computer. The cable can visit any of the towers (not just the ones between the computers) in an arbitrary order. It can skip towers by passing by without visiting them. It can also visit no towers at all and connect the two computers directly but it cannot connect a computer to itself. The number of computers is even.

Let aa and bb be the positions of two computers and let x1,,xkx_1,\ldots,x_k be positions of the towers the cable visits. The length of the cable is ax1+x1x2++xk1xk+xkb|a-x_1|+|x_1-x_2|+\cdots+|x_{k-1}-x_k|+|x_k-b|. For some cable we define its score as fulf\cdot u-l, where ll is its length, ff is some fixed constant and uu is the number of unique towers the cable visits among x1,,xkx_1,\ldots,x_k. Multiple cables can visit the same tower and that tower contributes to the score of each of those cables.

You need to compute the maximum possible sum of cable scores for pairing up all computers (i.e. each computer has to belong to exactly one pair, or equivalently, it must be connected to exactly one cable).

Input Format

The first line contains the number of test cases, TT. The test cases follow one after another. Each test case consists of three lines. The first line contains three integers nn, mm and ff - the number of computers, the number of towers and the constant ff. The second line contains nn integers a1,a2,,ana_1,a_2,\ldots,a_n - the positions of computers. The third line contains mm integers b1,b2,,bmb_1,b_2,\ldots,b_m - the positions of towers.

Output Format

Output TT integers, each on its own line - the maximum possible sum of scores of cables for each test case.

4
2 1 100
1 10
11
4 1 10
2 4 6 8
20
4 1 10
2 4 6 8
5
6 3 10
2 13 4 8 6 10
5 1 9
89
-4
12
51

Hint

Constraints

Let NN and MM be the sum of nn and mm through all test cases, respectively.

  • 1T1041\le T\le 10^4
  • 1N,M21051\le N,M\le 2\cdot 10^5
  • 0f1090\le f\le 10^9
  • nn is even
  • 1ai,bi1091\le a_i,b_i\le 10^9
  • All positions of computers and towers are unique (within an individual test case).

Subtasks

  • Subtask 11 (55 points): N5000N\le 5000, m=1m=1
  • Subtask 22 (1010 points): T20T\le 20, n10n\le 10, m100m\le 100
  • Subtask 33 (2727 points): N,M5000N,M\le 5000
  • Subtask 44 (2121 points): N5000N\le 5000
  • Subtask 55 (3737 points): No additional constraints.