差分是前缀和的逆运算
在二维前缀和 $S$ 中计算单个点$(i, j)$值的公式为
$$ a_{i, j} \ = \ S_{i, j} \ - \ S_{i, j - 1} \ - \ S_{i - 1, j} \ + \ S_{i - 1, j - 1} $$
因为在差分中是把原数组 $a$ 当成前缀和 $S$,差分数组 $b$ 为原数组,
所以更新原数组的时候就等于
$$ a_{i, j} \ = \ a_{i, j - 1} \ + \ a_{i - 1, j} \ - \ a_{i - 1, j - 1} \ + \ b_{i, j} $$
#include <iostream>
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()
{
cin >> n >> m >> q;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++)
cin >> a[i][j];
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++)
insert(i, j, i, j, a[i][j]);
while(q--)
{
int x1, y1, x2, y2, c;
cin >> 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++)
a[i][j] = a[i][j - 1] + a[i - 1][j] - a[i - 1][j - 1] + b[i][j];
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= m; j++)
printf("%d ", a[i][j]);
puts("");
}
}