Problem 213
Matrix Region Sum Queries
Medium · 20 pts · Matrix, Prefix Sum
Problem
You are given a matrix with R rows and C columns and Q queries. Each query r1 c1 r2 c2 asks for the sum of the rectangle whose top-left cell is (r1, c1) and bottom-right cell is (r2, c2), both included, using zero-based row and column numbers. Print each answer on its own line. Precompute 2D prefix sums, where P[i][j] is the sum of the rectangle from (0, 0) to (i - 1, j - 1). Each query is then answered with inclusion-exclusion: P[r2+1][c2+1] - P[r1][c2+1] - P[r2+1][c1] + P[r1][c1].
Input
First line: R and C. Next R lines: C integers. Then integer Q. Next Q lines: r1 c1 r2 c2.
Output
Print the answer to each query on its own line.
Constraints
1 <= R, C <= 500; -1000 <= value <= 1000; 1 <= Q <= 100000
Example input
3 3 1 2 3 4 5 6 7 8 9 2 0 0 1 1 1 1 2 2
Example output
12 28
Explanation
In the matrix 1 2 3 / 4 5 6 / 7 8 9, the first query covers the block 1 2 / 4 5, which sums to 12. The second covers 5 6 / 8 9, which sums to 28.