Under construction

Still being built. Things may change

Sum of submatrix maxima

Interview

Time limit20sMemory limit1024 MB

Summary
Add up the maximum value inside every K by K submatrix of an N by N matrix generated from two arrays.
Level

Medium5 of 10

Topics
Sliding window, Matrix, Queue
Solved
No attempts yet

Problem

You have an N×NN \times N matrix MM of nonnegative integers. For every K×KK \times K submatrix of MM, take the largest value inside it and write that value down. Submatrices may overlap, so the list holds (N−K+1)2(N-K+1)^2 values. One entry of MM can be the largest value of several submatrices, and then it appears in the list once for each of them. Compute the sum of the whole list.

Writing the matrix out would make the input huge, so you are given two arrays AA and BB of length NN together with two integers CC and XX instead. The value in row ii and column jj is

Mij=(Ai×i+Bj×j+C) mod XM_{ij} = (A_i \times i + B_j \times j + C) \bmod X

where ii and jj both run from 1 to NN.

Input

The first line holds the number of test cases TT. The TT test cases follow.

The first line of each test case holds four integers NN, KK, CC and XX, separated by spaces. The next two lines hold NN integers each: the first line is the array AA and the second line is the array BB.

Output

For each test case, print one line in the form Case #x: y, where xx is the test case number starting from 1 and yy is the sum of the maximum values of all K×KK \times K submatrices.

Constraints

  • 1≤T≤1001 \le T \le 100
  • 1≤N≤30001 \le N \le 3000
  • 1≤K≤N1 \le K \le N
  • 1≤Ai,Bi≤1000001 \le A_i, B_i \le 100000
  • 1≤C≤1000001 \le C \le 100000
  • 1≤X≤10000000071 \le X \le 1000000007

Hint

In the first test case of the example the matrix is

3

With K=1K = 1 there is a single submatrix, so the answer is 3.

In the second test case the matrix is

9 3
1 6

With K=1K = 1 each of the four entries is its own submatrix, so the answer is 9+3+1+6=199 + 3 + 1 + 6 = 19.

In the third test case the matrix is

11 11 24
13 13 26
14 14 27

With K=2K = 2 there are four submatrices whose maxima are 13, 26, 14 and 27, so the answer is 80.

Examples1

  1. Example 1

    Input
    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
    
    Expected output
    Case #1: 3
    Case #2: 19
    Case #3: 80