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

#PS0000233. Truy vấn tổng hai loại đường chéo (Two Diagonal Sum Queries)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Truy vấn tổng hai loại đường chéo (Two Diagonal Sum Queries)

Two Diagonal Sum Queries

Source: Phước Hưng OJ

Version: Phuoc Hung OJ Extended

Problem Statement

Given a static integer matrix of size n×mn\times m, indexed from 1, query (t,r,c,k)(t,r,c,k) asks for the sum of exactly kk cells including the start. For t=1t=1 the cells are (r+d,c+d)(r+d,c+d); for t=2t=2 they are (r+d,c−d)(r+d,c-d), where 0≤d<k0\le d<k. All queried cells lie inside the matrix.

Input

The first line contains n,m,Qn,m,Q, followed by nn rows of mm integers and QQ lines of t,r,c,kt,r,c,k.

Output

Print one diagonal sum per query.

Subtasks

  • Subtask 1 (20 points): 1≤n,m≤121\le n,m\le 12; ∣ai,j∣≤109|a_{i,j}|\le 10^9; 1≤Q≤301\le Q\le 30; t∈{1,2}t\in\{1,2\}; 1≤r≤n,1≤c≤m1\le r\le n,1\le c\le m; 1≤k≤n−r+11\le k\le n-r+1; k≤m−c+1k\le m-c+1 if t=1t=1; k≤ck\le c if t=2t=2.
  • Subtask 2 (30 points): 1≤n,m≤10001\le n,m\le 1000; ∣ai,j∣≤109|a_{i,j}|\le 10^9; 1≤Q≤2000001\le Q\le 200000; t∈{1,2}t\in\{1,2\}; 1≤r≤n,1≤c≤m1\le r\le n,1\le c\le m; 1≤k≤n−r+11\le k\le n-r+1; k≤m−c+1k\le m-c+1 if t=1t=1; k≤ck\le c if t=2t=2; t=1t=1.
  • Subtask 3 (50 points): 1≤n,m≤10001\le n,m\le 1000; ∣ai,j∣≤109|a_{i,j}|\le 10^9; 1≤Q≤2000001\le Q\le 200000; t∈{1,2}t\in\{1,2\}; 1≤r≤n,1≤c≤m1\le r\le n,1\le c\le m; 1≤k≤n−r+11\le k\le n-r+1; k≤m−c+1k\le m-c+1 if t=1t=1; k≤ck\le c if t=2t=2.

Example 1

Input

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

Output

15
15
12

Explanation

The queried diagonals are 1+5+9, 3+5+7 and 5+7.

Example 2

Input

1 1 2
-6
1 1 1 1
2 1 1 1

Output

-6
-6

Explanation

Each query contains the only cell.