Skip to content

Multiple dimensions

Forest Queries
CSES

This time, we have an analogue of the first problem — but on a grid AA of size N×NN \times N, as subrectangle queries. The naive solution would take O(QN2)O(QN^2) time, which is obviously too slow. The first obvious optimization would be to instead create a prefix sum array for each row, resulting in O(N2+QN)O(N^2 + QN) operations. This might be enough to pass for Q=2105Q = 2 \cdot 10^5 and N=1000N = 1000 as in the problem above, but we want an even faster solution.

Similar to what we did for the 1D version, we will build a “prefix matrix” PP, where P[i][j]P[i][j] is the sum of the subrectangle bounded by the cells (1,1)(1, 1) and (i,j)(i, j). To calculate this matrix, notice how we can sum P[i1][j]P[i - 1][j] and P[i][j1]P[i][j - 1], and then subtract P[i1][j1]P[i - 1][j - 1] as it was counted twice. Finally, we have to add A[i][j]A[i][j].


The green area is initially counted twice
123
456
789

Using this prefix matrix is similar to building it. Assume we wish to query the subrectangle (x,y,X,Y)(x, y, X, Y). After adding P[X][Y]P[X][Y] and subtracting both P[x1][Y]P[x - 1][Y] and P[X][y1]P[X][y-1] P[x1][y1]P[x-1][y-1] has been subtracted twice, so we add it once more. This gives us the formula

i=xXj=yYA[i][j]=P[X][Y]P[X][y1]P[x1][Y]+P[x1][y1] \sum_{i = x}^{X} \sum_{j=y}^{Y} A[i][j] = P[X][Y] - P[X][y - 1] - P[x - 1][Y] + P[x - 1][y - 1]

It is simple to generalize this further to MM dimensions using the Inclusion-Exclusion Principle.