Skip to main content
Tuesday (24.11.2026) at 20:00: ALGOR Contest: Round #4 (Special Challenge) starts!

~/algor $ cat problems/matritsa-qism-matritsa-yigindisi

Submatrix sum queries

Medium 2000 ms 128 MB 62%
Share

An integer matrix of size $n \times m$ and $q$ queries are given. Each query describes a rectangular submatrix with top-left corner $(r_{1}, c_{1})$ and bottom-right corner $(r_{2}, c_{2})$. Find the sum of the elements of that submatrix.

The sum of the elements in a given rectangular part of the matrix

Input

The first line contains $n$, $m$ and $q$. Each of the next $n$ lines contains $m$ integers. Each of the next $q$ lines contains four integers: $r_{1}, c_{1}, r_{2}, c_{2}$.

Output

For every query, one integer on its own line — the sum of the submatrix.

Note

$1 \le n, m \le 300$
$1 \le q \le 10^{5}$
$-1000 \le a_{i,j} \le 1000$
$1 \le r_{1} \le r_{2} \le n$
$1 \le c_{1} \le c_{2} \le m$

Examples

Input #1
3 3 3
1 2 3
4 5 6
7 8 9
1 1 3 3
2 2 3 3
1 2 2 2
Output #1
45
28
7
Input #2
1 2 2
5 -5
1 1 1 2
1 2 1 2
Output #2
0
-5

Sign in to submit a solution

Signing up is free and takes a minute.