2D prefix sums

A map may contain thousands of trees, and each query asks how many of them are inside a particular rectangle. Counting the trees one by one for every query can be too slow.

Two-dimensional prefix sums extend prefix sums to tables. After processing the entire table once, we can calculate the sum of any rectangular region in constant time.

Rectangle sums

Consider a table of 4 rows and 5 columns, numbered from 1. We want the sum of rows 3 through 4 and columns 3 through 5.

A table of 4 rows and 5 columns with rows 2 0 3 1 4, 1 5 2 0 3, 4 1 6 2 1 and 3 2 0 5 2; the six cells in rows 3 to 4, columns 3 to 5 (6, 2, 1, 0, 5, 2) are shaded blue.

Fig. 1. The question asks for the sum of the blue rectangle.

The six cells add up to 6+2+1+0+5+2=16. Repeating this process for many large rectangles may require operations for an by table and queries.

Let P[i][j] store the sum of the rectangle from cell (1, 1) to cell (i, j), inclusive. Row 0 and column 0 contain zeros, just like the empty prefix in a one-dimensional array.

Start with P[4][5] = 47, then subtract the area above the rectangle (P[2][5] = 21) and the area to its left (P[4][2] = 18). Their overlap (P[2][2] = 8) has been subtracted twice, so add it back once. The result is 47-21-18+8=16.

Left, the 4 by 5 table with rows 3 to 4, columns 3 to 5 shaded light blue; right, the table of its sums with a row 0 and a column 0 of zeros, where 47 and 8 are blue and 21 and 18 are red.

Fig. 2. The table and the table of its sums. The blue 47 and 8 are added and the red 21 and 18 are subtracted: 47 − 21 − 18 + 8 = 16.

For any inclusive rectangle with corners (r_1,c_1) and (r_2,c_2), the sum is

P_{r_2,c_2}-P_{r_1-1,c_2}-P_{r_2,c_1-1}+P_{r_1-1,c_1-1}.

This is an example of the inclusion–exclusion principle.

Building the prefix table

The same idea builds the table of sums. At cell , add its value 6, the prefix above it (13) and the prefix to its left (13), then subtract their overlap (8). The result is 6+13+13-8=24.

Two tables side by side: on the left the 4 by 5 table with cell (3, 3), value 6, in dark blue; on the right the table of its sums with rows and columns from 0, where the 13s at (2, 3) and (3, 2) are outlined blue, the rest of their rectangles is light blue, their overlap up to (2, 2), ending in 8, is red, and cell (3, 3) holds 24 in dark blue, because 6 + 13 + 13 − 8 = 24.

Fig. 3. The sum at cell (3, 3) is the cell plus the two blue rectangles, minus their red overlap.

The recurrence is

P_{i,j}=a_{i,j}+P_{i-1,j}+P_{i,j-1}-P_{i-1,j-1}.

Process rows from top to bottom and columns from left to right. This guarantees that the three earlier prefix sums are already available.

Implementation

vector<vector<long long>> P(n + 1, vector<long long>(m + 1));

for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
        P[i][j] = a[i][j] + P[i - 1][j]
                + P[i][j - 1] - P[i - 1][j - 1];
    }
}

We use one-based indices for the original table. The extra row and column of zeros in P allow the same formula to work for every rectangle, including those starting at the first row or column.

long long sum = P[r2][c2] - P[r1 - 1][c2]
              - P[r2][c1 - 1] + P[r1 - 1][c1 - 1];

The query uses inclusive boundaries: 1 <= r1 <= r2 <= n and 1 <= c1 <= c2 <= m.

Reading and answering queries

The program reads n and m, the table row by row, and then q rectangle queries.

Input:

4 5
2 0 3 1 4
1 5 2 0 3
4 1 6 2 1
3 2 0 5 2
2
3 3 4 5
2 2 4 4

Output:

16
23
#include <iostream>
#include <vector>
using namespace std;

int main() {
    // fast input: needed for a million questions
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n, m;
    cin >> n >> m;
    vector<vector<long long>> P(n + 1, vector<long long>(m + 1, 0));
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= m; j++) {
            // read
            long long x;
            cin >> x;
            // build
            P[i][j] = x + P[i - 1][j] + P[i][j - 1] - P[i - 1][j - 1];
        }

    // answer
    int q;
    cin >> q;
    while (q--) {
        int r1, c1, r2, c2;
        cin >> r1 >> c1 >> r2 >> c2;
        cout << P[r2][c2] - P[r1 - 1][c2] - P[r2][c1 - 1] + P[r1 - 1][c1 - 1] << '\n';
    }
}

Building the prefix table takes time and memory (about 8 MB for a 1000\times1000 table of long long). Each query takes time, giving O(nm+q) time for the whole program.

Examples of use

Counting marked cells

A map shows trees as * and empty plots as ., one row per line. Build P over 1 for a tree and 0 for an empty plot, and the four terms count the trees in any rectangle.

// read row i of the map as a string s; cell (i, j) is s[j - 1]
// build
P[i][j] = (s[j - 1] == '*') + P[i - 1][j] + P[i][j - 1] - P[i - 1][j - 1];

The best k×k square

For a fixed square size k (1 <= k <= min(n, m)), enumerate all possible bottom-right cells. Each square can be evaluated in constant time using the prefix table, so finding the largest sum takes time. On the first table, the best 2 by 2 square ends at (3, 3) and has sum 24-5-7+2=14.

long long best = LLONG_MIN;   // needs <climits>
for (int i = k; i <= n; i++)
    for (int j = k; j <= m; j++)
        best = max(best, P[i][j] - P[i - k][j] - P[i][j - k] + P[i - k][j - k]);

Two-dimensional difference arrays

A two-dimensional difference array handles many rectangle additions when the final table is needed only after all updates. Just as a one-dimensional difference array uses two boundary updates, a rectangle uses four.

A mark at (i, j) changes the value of every cell below and to the right of it. So a rectangle needs +x at its top-left cell, -x right after its last column, -x right after its last row, and +x where both minus marks act. Index r2 + 1 can be n + 1, so d has n + 2 rows and m + 2 columns.

Each change costs , and the final build O(n \cdot m). Here P is a new table, built from d instead of a.

vector<vector<long long>> d(n + 2, vector<long long>(m + 2, 0));
// mark, for each change r1 c1 r2 c2 x
d[r1][c1] += x;
d[r1][c2 + 1] -= x;
d[r2 + 1][c1] -= x;
d[r2 + 1][c2 + 1] += x;
// After all updates, reconstruct the final table.
vector<vector<long long>> P(n + 1, vector<long long>(m + 1));
for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
        P[i][j] = d[i][j] + P[i - 1][j]
                + P[i][j - 1] - P[i - 1][j - 1];
    }
}

For example, a 4×5 table of zeros gets 3 added to rows 2–3, columns 2–4, and 1 added to rows 3–4, columns 3–5.

Left, the 5 by 6 table d with the marks added so far, plus marks blue and minus marks red; right, the 4 by 5 table of values they produce: the four marks of the first change one by one leave 3 in rows 2 to 3, columns 2 to 4, and the four marks of the second change add 1 to rows 3 to 4, columns 3 to 5, so the overlap holds 4.

+3 at (2, 2): everything below and to the right gets 3.

1/5

Fig. 4. Step through the marks with the buttons or the arrow keys. Each mark changes every value below and to the right of it.

Common mistakes

Similar techniques

When point updates are mixed with rectangle-sum queries, rebuilding P costs per update. A 2D Fenwick tree supports these operations in O(\log n\log m) time.

A sparse table answers the minimum or maximum of a range. A minimum can't be subtracted away, so P doesn't help there.

For the largest sum over all rectangles, trying each one with P is O(n^2 m^2). Fix two rows, add up each column between them, and find the maximum subarray of that row: O(n^2 m).

Practice

Bu səhifə faydalı oldumu?