Range Sum Queries on a 2D Grid

easy prefix-sums arrays 1000 ms · 256 MB

Range Sum Queries on a 2D Grid

You are given a grid of integers with n rows and m columns. Rows are numbered from 1 to n top to bottom, columns from 1 to m left to right, and the cell in row i and column j holds the value a_{i,j}. Values may be negative.

Then q queries follow. Each query names two cells (r1, c1) and (r2, c2) that are opposite corners of an axis-aligned rectangle. The two corners can be given in any order: r1 may be larger than r2, and c1 may be larger than c2. The rectangle contains every cell (i, j) with i between r1 and r2 and j between c1 and c2, both inclusive. The two corners may be the same cell, and the rectangle may be a single row or a single column.

For each query, print the sum of the values of all cells inside its rectangle.

Input

The first line contains three integers n, m and q (1 ≤ n, m ≤ 1000, 1 ≤ q ≤ 2·10^5).

Each of the next n lines contains m integers a_{i,1}, …, a_{i,m} (−10^6 ≤ a_{i,j} ≤ 10^6).

Each of the next q lines contains four integers r1, c1, r2, c2 (1 ≤ r1, r2 ≤ n, 1 ≤ c1, c2 ≤ m).

Output

Print q lines. The k-th line must contain a single integer: the sum of the cells inside the rectangle of the k-th query.

Notes

In the first example the grid is

 1   2   3   4
 5  -6   7   8
 9  10 -11  12

The first query covers the whole grid, whose sum is 44. The third query 3 1 2 2 lists its corners bottom-first: it covers rows 2..3 and columns 1..2, so the answer is 5 − 6 + 9 + 10 = 18. The last query 3 4 1 3 covers rows 1..3 and columns 3..4.

A sum can be as large as 10^12 in absolute value, which does not fit in a 32-bit integer.

Example 1

Input

3 4 5
1 2 3 4
5 -6 7 8
9 10 -11 12
1 1 3 4
2 2 3 3
3 1 2 2
1 4 1 4
3 4 1 3

Output

44
0
18
4
23

Example 2

Input

2 3 3
-1000000 -1000000 -1000000
1000000 1000000 1000000
1 1 2 3
2 3 2 1
1 2 1 2

Output

0
3000000
-1000000

Hints · reveal one at a time if you're stuck

Hint 1

Summing each rectangle cell by cell is far too slow with 2·10^5 queries. Could you precompute something about the grid once, so that any rectangle's sum is built from a few stored values?

Hint 2

Store the sum of every block that starts at the top-left corner, with a zero border so the edges need no special cases. Then build each rectangle from four stored blocks with inclusion-exclusion. Normalise the corners first, since they can come in any order, and use 64-bit values.

report an issue Prefer your own editor? sooks prep 20 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.