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

#PS0000232. Tổng lưới 3D ngoài một hình hộp (Sum Outside a Cuboid)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Tổng lưới 3D ngoài một hình hộp (Sum Outside a Cuboid)

Sum Outside a Cuboid

Source: Phước Hưng OJ

Version: Phuoc Hung OJ Extended

Problem Statement

Given an integer cube of size n×n×nn\times n\times n, each query specifies an inclusive cuboid [x1,x2]×[y1,y2]×[z1,z2][x_1,x_2]\times[y_1,y_2]\times[z_1,z_2]. Return the sum of all cells outside that cuboid. Coordinates are 1-based and the cube is static.

Input

The first line contains n,Qn,Q. The next n2n^2 lines contain the cube: row (x−1)n+y(x-1)n+y contains ax,y,1,…,ax,y,na_{x,y,1},\ldots,a_{x,y,n}. Each of the next QQ lines contains x1,x2,y1,y2,z1,z2x_1,x_2,y_1,y_2,z_1,z_2.

Output

Print QQ lines, one outside sum per query.

Subtasks

  • Subtask 1 (20 points): 1≤n≤51\le n\le 5; ∣ai,j∣≤109|a_{i,j}|\le 10^9; 1≤Q≤301\le Q\le 30; 1≤x1≤x2≤n1\le x_1\le x_2\le n; 1≤y1≤y2≤n1\le y_1\le y_2\le n; 1≤z1≤z2≤n1\le z_1\le z_2\le n.
  • Subtask 2 (30 points): 1≤n≤601\le n\le 60; ∣ai,j∣≤109|a_{i,j}|\le 10^9; 1≤Q≤1000001\le Q\le 100000; 1≤x1≤x2≤n1\le x_1\le x_2\le n; 1≤y1≤y2≤n1\le y_1\le y_2\le n; 1≤z1≤z2≤n1\le z_1\le z_2\le n; x1=x2,y1=y2,z1=z2x_1=x_2,y_1=y_2,z_1=z_2.
  • Subtask 3 (50 points): 1≤n≤601\le n\le 60; ∣ai,j∣≤109|a_{i,j}|\le 10^9; 1≤Q≤1000001\le Q\le 100000; 1≤x1≤x2≤n1\le x_1\le x_2\le n; 1≤y1≤y2≤n1\le y_1\le y_2\le n; 1≤z1≤z2≤n1\le z_1\le z_2\le n.

Example 1

Input

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

Output

26
0
28

Explanation

The cube sums to 36. Cuboid sums are 10,36,8, giving outside sums 26,0,28.

Example 2

Input

1 1
-5
1 1 1 1 1 1

Output

0

Explanation

The cuboid covers the entire cube.