Partial Sums of a Triangle
InterviewTime limit1sMemory limit1024 MB
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 beads in total. The grid has rows. Going down, each row holds more beads, so the -th row from the top has 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 .
The next lines each contain integers separated by spaces for the -th line. is the number on the bead at position from the left in the -th row from the top.
The next line contains the number of partial triangles .
The next lines each contain three integers , , and separated by spaces, which determine a partial triangle.
Output
For each given , , and , print on its own line the sum of the numbers on the beads inside the partial triangle defined as follows.
- For every integer with , the triangle includes the beads in row from the top, from the -th bead to the -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.