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

#PS0000219. Truy vấn tổng hình hộp chữ nhật (Cuboid Sum Query)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Truy vấn tổng hình hộp chữ nhật (Cuboid Sum Query)

Cuboid Sum Query

Source: AtCoder

Version: Phuoc Hung OJ Extended

Problem Statement

An N×N×NN\times N\times N array AA is indexed from 1 on all three axes. Each query gives Lx,Rx,Ly,Ry,Lz,RzL_x,R_x,L_y,R_y,L_z,R_z. Return the sum of cells with coordinates inside the three inclusive intervals. The array is static.

Input

The first line contains NN. The next N2N^2 lines each contain NN integers: line (x−1)N+y(x-1)N+y of this block contains Ax,y,1,…,Ax,y,NA_{x,y,1},\ldots,A_{x,y,N}. The next line contains QQ, followed by QQ lines in the order Lx,Rx,Ly,Ry,Lz,RzL_x,R_x,L_y,R_y,L_z,R_z.

Output

Print QQ lines in query order, each the requested cuboid sum.

Subtasks

  • Subtask 1 (20 points): 1≤N≤61\le N\le 6; 1≤Q≤301\le Q\le 30; 0≤Ax,y,z≤9990\le A_{x,y,z}\le999; 1≤Lx≤Rx≤N1\le L_x\le R_x\le N; 1≤Ly≤Ry≤N1\le L_y\le R_y\le N; 1≤Lz≤Rz≤N1\le L_z\le R_z\le N.
  • Subtask 2 (30 points): 1≤N≤1001\le N\le 100; 1≤Q≤2000001\le Q\le 200000; 0≤Ax,y,z≤9990\le A_{x,y,z}\le999; 1≤Lx≤Rx≤N1\le L_x\le R_x\le N; 1≤Ly≤Ry≤N1\le L_y\le R_y\le N; 1≤Lz≤Rz≤N1\le L_z\le R_z\le N; Lx=Rx,Ly=Ry,Lz=RzL_x=R_x, L_y=R_y, L_z=R_z.
  • Subtask 3 (50 points): 1≤N≤1001\le N\le 100; 1≤Q≤2000001\le Q\le 200000; 0≤Ax,y,z≤9990\le A_{x,y,z}\le999; 1≤Lx≤Rx≤N1\le L_x\le R_x\le N; 1≤Ly≤Ry≤N1\le L_y\le R_y\le N; 1≤Lz≤Rz≤N1\le L_z\le R_z\le N.

Example 1

Input

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

Output

10
26

Explanation

The first query sums 3 and 7. The second takes all four cells with x=2.

Example 2

Input

3
733 857 714
956 208 257
123 719 648
840 881 245
245 112 746
306 942 694
58 870 849
13 208 789
687 906 783
8
3 3 3 3 1 1
1 3 2 3 3 3
2 2 2 3 1 1
1 3 1 1 1 1
2 3 2 3 2 3
1 2 1 1 1 2
3 3 2 2 1 3
1 2 2 3 2 3

Output

687
3917
551
1631
5180
3311
1010
4326

Explanation

The first query takes cell (3,3,1), value 687. The third sums 245 and 306. The remaining queries sum their respective cuboids.