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

#PS0000231. Tổng hình vuông xoay 45 độ (Rotated Square Sum)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Tổng hình vuông xoay 45 độ (Rotated Square Sum)

Rotated Square Sum

Source: Phước Hưng OJ

Version: Phuoc Hung OJ Extended

Problem Statement

Given a static integer n×nn\times n matrix indexed from 1, each query (r,c,K)(r,c,K) asks for the sum of cells (i,j)(i,j) satisfying ∣i−r∣+∣j−c∣≤K|i-r|+|j-c|\le K. Ignore positions outside the matrix.

Input

The first line contains n,Qn,Q, followed by nn rows of nn integers. Each of the next QQ lines contains r,c,Kr,c,K.

Output

Print QQ lines, one diamond sum per query.

Subtasks

  • Subtask 1 (20 points): 1≤n≤121\le n\le 12; −109≤ai,j≤109-10^9\le a_{i,j}\le10^9; 1≤Q≤301\le Q\le 30; 1≤r,c≤n1\le r,c\le n; 0≤K≤2n0\le K\le2n.
  • Subtask 2 (30 points): 1≤n≤5001\le n\le 500; −109≤ai,j≤109-10^9\le a_{i,j}\le10^9; 1≤Q≤1000001\le Q\le 100000; 1≤r,c≤n1\le r,c\le n; 0≤K≤2n0\le K\le2n; K=0K=0.
  • Subtask 3 (50 points): 1≤n≤5001\le n\le 500; −109≤ai,j≤109-10^9\le a_{i,j}\le10^9; 1≤Q≤1000001\le Q\le 100000; 1≤r,c≤n1\le r,c\le n; 0≤K≤2n0\le K\le2n.

Example 1

Input

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

Output

25
7
45

Explanation

The first diamond includes 2,4,5,6,8. The corner includes 1,2,4. The last query covers the grid.

Example 2

Input

1 1
-9
1 1 2

Output

-9

Explanation

Only the cell −9 lies in the grid.