PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#PS0000209. Tổng hình chữ nhật trên ma trận tĩnh (Range Sum Query 2D - Immutable)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Tổng hình chữ nhật trên ma trận tĩnh (Range Sum Query 2D - Immutable)

Range Sum Query 2D - Immutable

Source: LeetCode

Version: Phuoc Hung OJ Extended

Problem Statement

Given a static integer matrix AA with mm rows and nn columns, indexed from 0, return the sum of all entries in each inclusive rectangle from (r1,c1)(r_1,c_1) to (r2,c2)(r_2,c_2). Values may be negative. Aim for O(1)O(1) query time after preprocessing.

Input

The first line contains m,n,qm,n,q. The next mm lines each contain nn integers Ai,jA_{i,j}. The following qq lines contain r1,c1,r2,c2r_1,c_1,r_2,c_2.

Output

Print qq lines, one rectangle sum per query.

Subtasks

  • Subtask 1 (20 points): 1≤m,n≤151\le m,n\le 15; 1≤q≤401\le q\le 40; ∣Ai,j∣≤104|A_{i,j}|\le10^4; 0≤r1≤r2<m0\le r_1\le r_2<m; 0≤c1≤c2<n0\le c_1\le c_2<n.
  • Subtask 2 (30 points): 1≤m,n≤2001\le m,n\le 200; 1≤q≤100001\le q\le 10000; ∣Ai,j∣≤104|A_{i,j}|\le10^4; 0≤r1≤r2<m0\le r_1\le r_2<m; 0≤c1≤c2<n0\le c_1\le c_2<n; r1=r2r_1=r_2.
  • Subtask 3 (50 points): 1≤m,n≤2001\le m,n\le 200; 1≤q≤100001\le q\le 10000; ∣Ai,j∣≤104|A_{i,j}|\le10^4; 0≤r1≤r2<m0\le r_1\le r_2<m; 0≤c1≤c2<n0\le c_1\le c_2<n.

Example 1

Input

5 5 3
3 0 1 4 2
5 6 3 2 1
1 2 0 1 5
4 1 0 1 7
1 0 3 0 5
2 1 4 3
1 1 2 2
1 2 2 4

Output

8
11
12

Explanation

The sums are (2+0+1)+(1+0+1)+(0+3+0)=8, (6+3)+(2+0)=11, and (3+2+1)+(0+1+5)=12.

Example 2

Input

2 3 2
-2 0 3
5 -4 1
0 0 1 2
0 0 0 0

Output

3
-2

Explanation

The full matrix sums to 3; cell (0,0) is -2.