#P16513. [GKS 2015 #C] gMatrix

[GKS 2015 #C] gMatrix

Problem Description

You have a square NN by NN matrix MM of nonnegative integers. We would like to make a list of the maximum values in every sub-matrix of size KK by KK within MM, and then find the sum of those values together. (Note that the same entry of MM might be the maximum value in more than one sub-matrix, in which case it will show up multiple times in the list.) Can you find that sum?

To simplify the input of the matrix, you are given two arrays A\mathbf{A} and B\mathbf{B} of length NN, and two integers C\mathbf{C} and X\mathbf{X}. Then the entry MijM_{ij} (for the iith row and jjth column of the matrix) equals $(\mathbf{A}_i \times i + \mathbf{B}_j \times j + \mathbf{C}) \pmod{\mathbf{X}}$, where ii and jj are in the range [1,N][1, N].

Input Format

The first line of the input gives the number of test cases, TT. TT test cases follow. Each test case begins with one line with four integers, NN, KK, CC and XX. Then there are two lines with NN integers each, representing the arrays A\mathbf{A} and B\mathbf{B}.

Output Format

For each test case, output one line containing "Case #x: y", where x is the test case number (starting from 1) and yy is the sum of the maximum values in all sub-matrices of size KK by KK.

3
1 1 1 5
1
1
2 1 5 11
1 2
3 4
3 2 3 109
6 4 3
2 1 5
Case #1: 3
Case #2: 19
Case #3: 80

Hint

In the first test case, the matrix is:

3

So the sum of maximum values is 33.

In the second test case, the matrix is:

9 3
1 6

So the sum of maximum values is 1919.

In the third test case, the matrix is:

11 11 24
13 13 26
14 14 27

Limits

1T1001 \le T \le 100.

1Ai,Bi1000001 \le A_i, B_i \le 100000.

1C1000001 \le C \le 100000.

1X10000000071 \le X \le 1000000007.

1KN1 \le K \le N.

Small dataset (Test Set 1 - Visible)

1N501 \le N \le 50.

Large dataset (Test Set 2 - Hidden)

1N30001 \le N \le 3000.