Triangular Summation#11863

Triangular Summation

2 seconds
256 megabytes
Very hard

You are given a n \times m grid, where each cell contains a value A_{i,j}.

C_{i,j} = \min(i, n+1-i, j, m+1-j) \cdot A_{i,j}

The cost of a cell in the -th row and -th column is defined as:

Find the sum of the costs of all the cells in the grid.

You are given queries. In each query, you are given two pairs of integers (l_1, r_1) and (l_2, r_2), representing a subgrid from rows l_1 to l_2 and columns r_1 to r_2.

Note: In each query, treat the subgrid as a new independent grid. That is, start indexing from (not from (l_1, r_1)). For this subgrid, consider its dimensions as n = l_2 - l_1 + 1, m = r_2 - r_1 + 1.

^{\dagger} The Manhattan distance between two points (x_1, y_1) and (x_2, y_2) is defined by |x_1 - x_2| + |y_1 - y_2|.

Input

The first line contains a single integer (1 \le t \le 10^4) — the number of test cases.

Each test case starts with a line containing two integers and (1 \le n \times m \le 10^6) — the dimensions of the grid.

The next lines each contain integers: A_{i,1}, \ldots, A_{i,m} (1 \le A_{i,j} \le 1000) — the values of the grid.

The next line contains a single integer (1 \le q \le 10^6) — the number of queries.

The next lines each contain four integers l_1, r_1, l_2, r_2 (1 \le l_1 \le l_2 \le n, 1 \le r_1 \le r_2 \le m).

It is guaranteed that the sum of n \cdot m + q over all test cases does not exceed 2 \cdot 10^6.

Output

For each test case, for each query, print a single integer: the sum of the costs for the selected subgrid.

Examples

Example 1

Loading
Loading

Note

Let denote the original grid given in the input and the contributions array (the new independent grid in the subgrid query).

A = \begin{bmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \end{bmatrix} \quad B = \begin{bmatrix} 1 & 1 & 1 \\ 1 & 2 & 1 \\ 1 & 1 & 1 \end{bmatrix}

For the first test case:

  1. Query --: whole grid. Answer: .

  2. Query --: subgrid 3 \times 2, all w_{ij} = 1. Sum =1+2+4+5+7+8=27.

  3. Query --: subgrid 2 \times 3, all w_{ij} = 1. Sum =1+2+3+4+5+6=21.

Scoring

  1. Subtask ( points): q=1.

  2. Subtask ( points): 1 \le \sum n \cdot m \le 1000.

  3. Subtask ( points): A_{i,j} is identical for the whole grid.

  4. Subtask ( points): l_2-l_1 \le 3.

  5. Subtask ( points): all values in each row are equal.

  6. Subtask ( points): \sum q \le 1000.

  7. Subtask ( points): No additional constraints.