templates/partial-sum-2d.cpp
compilable
$cat templates/partial-sum-2d
Partial Sum 2D (Difference Array)
2D difference array for O(1) range updates and O(n*m) final propagation.
#difference-array#2d#range-update#partial-sum
Log in to track progress, save custom versions, and organize into collections.Log In
$cat source_code/
cpp
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int MAXN = 1005;
ll diff[MAXN][MAXN];
int N, M;
void update(int x1, int y1, int x2, int y2, ll k = 1) {
if (x1 > x2) swap(x1, x2);
if (y1 > y2) swap(y1, y2);
diff[x2][y2] += k;
diff[x2][y1 - 1] -= k;
diff[x1 - 1][y2] -= k;
diff[x1 - 1][y1 - 1] += k;
}
void propagate() {
for (int i = N; i >= 0; i--)
for (int j = M; j >= 0; j--)
diff[i][j] += diff[i][j + 1];
for (int i = N; i >= 0; i--)
for (int j = M; j >= 0; j--)
diff[i][j] += diff[i + 1][j];
}
ll get(int x, int y) {
return diff[x][y];
}29 linesutf-8
$cat explanation_notes.md
notes_viewer --renderedmarkdown (math enabled)
2D Difference Array
Batch rectangle updates in each, then propagate once to get the final grid.
How It Works
To add to every cell in rectangle to , mark four corners:
After all updates, propagate with two passes: