You are given an integer grid with R rows and C columns (1-indexed). Then you must answer Q queries. Each query gives the top-left corner (r1, c1) and bottom-right corner (r2, c2) of an axis-aligned rectangle, and asks for the sum of all grid values inside that rectangle, inclusive on all four sides. It is guaranteed that 1 ≤ r1 ≤ r2 ≤ R and 1 ≤ c1 ≤ c2 ≤ C for every query.
R and C.R lines: each contains C space-separated integers — the grid, row by row.Q.Q lines: each contains four integers r1 c1 r2 c2 (1-indexed, inclusive).Print Q lines. Line i is the sum of the submatrix requested by the i-th query.
Example 1
Input
3 4 1 2 3 4 5 6 7 8 9 10 11 12 2 1 1 2 2 2 3 3 4
Expected
14 38
Explanation
Query 1 covers rows 1-2, cols 1-2: 1+2+5+6 = 14. Query 2 covers rows 2-3, cols 3-4: 7+8+11+12 = 38.
Example 2
Input
2 2 -1 -2 -3 -4 2 1 1 1 1 1 1 2 2
Expected
-1 -10
Explanation
Query 1 is the single cell (1,1) = -1. Query 2 is the whole grid: -1 + -2 + -3 + -4 = -10.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →