atcoder#ARC133C. [ARC133C] Row Column Sums

[ARC133C] Row Column Sums

Score : 500500 points

Problem Statement

We have a grid with HH rows and WW columns.

Snuke is going to write in each square an integer between 00 and K1K-1 (inclusive). Here, the conditions below must be satisfied.

  • For each 1iH1 \leq i \leq H, the sum modulo KK of the integers written in the ii-th row is AiA_i.
  • For each 1iW1 \leq i \leq W, the sum modulo KK of the integers written in the ii-th column is BiB_i.

Determine whether it is possible to write integers in the squares to satisfy the conditions. If it is possible, also find the maximum possible sum of the integers written.

Constraints

  • 1H,W2000001 \leq H,W \leq 200000
  • 2K2000002 \leq K \leq 200000
  • 0AiK10 \leq A_i \leq K-1
  • 0BiK10 \leq B_i \leq K-1
  • All values in input are integers.

Input

Input is given from Standard Input in the following format:

HH WW KK

A1A_1 A2A_2 \cdots AHA_H

B1B_1 B2B_2 \cdots BWB_W

Output

If it is impossible to write integers in the squares to satisfy the conditions, print -1. If it is possible, print the maximum possible sum of the integers written.

2 4 3
0 2
1 2 2 0
11

The following should be written.

-----------------
| 2 | 0 | 2 | 2 |
-----------------
| 2 | 2 | 0 | 1 |
-----------------

We can see that the conditions are satisfied. For example, the sum of the integers in the 11-st row is 66, which modulo K(=3)K(=3) is A1(=0)A_1(=0).

The sum of the integers written here is 1111, which is the maximum possible value.

3 3 4
0 1 2
1 2 3
-1