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

#PS0000222. Truy vấn tổng vùng Manhattan (Rotated Coordinates)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Truy vấn tổng vùng Manhattan (Rotated Coordinates)

Rotated Coordinates

Source: Phước Hưng OJ

Version: Phuoc Hung OJ Extended

Problem Statement

Given a static weighted m×nm\times n matrix indexed from 1, each query (r,c,k)(r,c,k) asks for the sum of all cells (i,j)(i,j) inside the matrix satisfying ∣i−r∣+∣j−c∣≤k|i-r|+|j-c|\le k, including the center. Weights may be negative.

Input

The first line contains m,n,Qm,n,Q, followed by mm rows of nn integers. Each of the next QQ lines contains r,c,kr,c,k.

Output

Print QQ lines, one answer per query.

Subtasks

  • Subtask 1 (20 points): 1≤m,n≤101\le m,n\le 10; 1≤Q≤301\le Q\le 30; ∣ai,j∣≤109|a_{i,j}|\le10^9; 1≤r≤m1\le r\le m; 1≤c≤n1\le c\le n; 0≤k≤m+n0\le k\le m+n.
  • Subtask 2 (30 points): 1≤m,n≤5001\le m,n\le 500; 1≤Q≤1000001\le Q\le 100000; ∣ai,j∣≤109|a_{i,j}|\le10^9; 1≤r≤m1\le r\le m; 1≤c≤n1\le c\le n; 0≤k≤m+n0\le k\le m+n; k=0k=0.
  • Subtask 3 (50 points): 1≤m,n≤5001\le m,n\le 500; 1≤Q≤1000001\le Q\le 100000; ∣ai,j∣≤109|a_{i,j}|\le10^9; 1≤r≤m1\le r\le m; 1≤c≤n1\le c\le n; 0≤k≤m+n0\le k\le m+n.

Example 1

Input

3 3 3
1 2 3
4 5 6
7 8 9
2 2 1
1 1 1
1 1 6

Output

25
7
45

Explanation

The first query includes the center and four neighbors. The second includes three cells. The third covers the entire grid.

Example 2

Input

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

Output

3
-3

Explanation

Radius zero selects 3; radius one selects the entire row.