能解决什么问题
快速的区间操作
算法思想
给定 a[1], a[2], ..., a[n],构造差分数组 b[1], b[2], ..., b[n],使得 a[i] = b[1] + b[2] + ... + b[i]。此时,如果将 a 数组 [l, r] 区间同时加上 c,等价于 b[l] += c,b[r + 1] -= c。
一维差分
#include <cstdio>
using namespace std;
const int N = 1e5 + 10;
int n, m;
int a[N], b[N];
void insert(int l, int r, int c)
{
b[l] += c;
b[r + 1] -= c;
}
int main()
{
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
insert(i, i, a[i]); // 相当于在 [i, i] 上加 a[i]
}
while (m--) {
int l, r, c;
scanf("%d%d%d", &l, &r, &c);
insert(l, r, c);
}
for (int i = 1; i <= n; i++) {
b[i] += b[i - 1]; // 求前缀和得到操作后的数组
printf("%d ", b[i]);
}
return 0;
}
二维差分
#include <cstdio>
using namespace std;
const int N = 1010;
int n, m, q;
int a[N][N], b[N][N];
void insert(int x1, int y1, int x2, int y2, int c)
{
b[x1][y1] += c;
b[x1][y2 + 1] -= c;
b[x2 + 1][y1] -= c;
b[x2 + 1][y2 + 1] += c;
}
int main()
{
scanf("%d%d%d", &n, &m, &q);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++) {
scanf("%d", &a[i][j]);
insert(i, j, i, j, a[i][j]);
}
while (q--) {
int x1, y1, x2, y2, c;
scanf("%d%d%d%d%d", &x1, &y1, &x2, &y2, &c);
insert(x1, y1, x2, y2, c);
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
b[i][j] += b[i - 1][j] + b[i][j - 1] - b[i - 1][j - 1];
printf("%d ", b[i][j]);
}
puts("");
}
return 0;
}
三维差分
int b[A][B][C];
// 对于 insert 函数奇数个 1 是负号
int d[8][4] = {
{0, 0, 0, 1};
{0, 0, 1, -1};
{0, 1, 0, -1};
{0, 1, 1, 1};
{1, 0, 0, -1};
{1, 0, 1, 1};
{1, 1, 0, 1};
{1, 1, 1, -1};
};
// 是 1 的那位要变为二号点
void insert(int x1, int y1, int z1, int x2, int y2, int z2, int c)
{
b[x1][y1][z1] += c;
b[x1][y1][z2 + 1] -= c;
b[x1][y2 + 1][z1] -= c;
b[x1][y2 + 1][z2 + 1] += c;
b[x2 + 1][y1][z1] -= c;
b[x2 + 1][y1][z2 + 1] += c;
b[x2 + 1][y2 + 1][z1] += c;
b[x2 + 1][y2 + 1][z2 + 1] -= c;
}
void get_pre_sum(int i, int j, int k)
{
for (int u = 1; u < 8; u++) {
int x = i - d[u][0], y = j - d[u][1], z = k - d[u][2], t = -d[u][3]; // 求前缀和时除了 {0, 0, 0},奇数个 1 是正号
b[i][j][k] += b[x][y][z] * t;
}
}