Under construction

Still being built. Things may change

Partial Sums of a Triangle

Interview

Time limit1sMemory limit1024 MB

Summary
Given a triangular grid of numbers, answer up to 500,000 queries that each ask for the sum of a sub-triangle with apex at (x, y) and height z.
Level

Medium6 of 10

Topics
Prefix sum, Array, Implementation
Solved
No attempts yet

Problem

Beads are arranged in a triangular grid as shown in the figure, so there are N(N+1)2\frac{N(N+1)}{2} beads in total. The grid has NN rows. Going down, each row holds more beads, so the ii-th row from the top has ii beads.

Each bead has one number written on it. Each time a partial triangle on this grid is given, write a program that prints the sum of the numbers on the beads inside that partial triangle.

Input

The first line contains the number of rows NN. (2≤N≤1 500)(2 \le N \le 1\,500)

The next NN lines each contain ii integers ai1,ai2,…,aiia_{i1}, a_{i2}, \ldots, a_{ii} separated by spaces for the ii-th line. aija_{ij} is the number on the bead at position jj from the left in the ii-th row from the top. (0≤aij≤500 000)(0 \le a_{ij} \le 500\,000)

The next line contains the number of partial triangles QQ. (1≤Q≤500 000)(1 \le Q \le 500\,000)

The next QQ lines each contain three integers xx, yy, and zz separated by spaces, which determine a partial triangle. (1≤x≤N; 1≤y≤x; 2≤z≤N−x+1)(1 \le x \le N;\ 1 \le y \le x;\ 2 \le z \le N - x + 1)

Output

For each given xx, yy, and zz, print on its own line the sum of the numbers on the beads inside the partial triangle defined as follows.

  • For every integer ii with 0≤i≤z−10 \le i \le z - 1, the triangle includes the beads in row x+ix+i from the top, from the yy-th bead to the (y+i)(y+i)-th bead counted from the left.

Hint

In languages such as C/C++ and Java, declaring some variables as 32-bit integers can cause overflow.

Examples2

  1. Example 1

    Input
    4
    1
    2 3
    4 5 6
    7 8 9 10
    6
    1 1 4
    2 1 3
    2 2 3
    3 1 2
    3 2 2
    3 3 2
    
    Expected output
    55
    35
    41
    19
    22
    25
    
  2. Example 2

    Input
    2
    1
    500000 1
    2
    1 1 2
    1 1 2
    
    Expected output
    500002
    500002