学习目标:
No.7差分与差分矩阵
学习内容:
原数组有a1,a2, …, an
构造新的数组b1, b2, …,bn
使得ai = b1 + b2 + … + bi
即b1= a1,b2 = a2 - a1, b3 = a3 - a2, …, bn = an - an-1
a是b数组的前缀和,b是a数组的差分。相当于高数中积分和微分的关系
假如我们想把a数组l到r区间内的所有数都加上C,只需要在b数组中,bl + C,此时al到an都会加上C,我们并不想让a数组的r到n区间也加上C,所以只需要br + 1 - C即可。
我们假定每一项都是0,第一步先把a1到an放进去,就是在区间1到1加上a1, 2到2加上a2…以此类推n到n加上an。所以,差分的时候我们只需要考虑b数组的两个步骤即可,其他的都不用考虑了
一维差分模板:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1000010;
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]);
for (int i = 1; i <= n; i ++ ) insert(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];
for (int i = 1; i <= n; i ++ ) printf("%d ", b[i]);
return 0;
}
二维差分模板(差分矩阵):
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
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[x2 + 1][y1] -= c;
b[x1][y2 + 1] -= 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]);
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 ++ )
b[i][j] += b[i - 1][j] + b[i][j - 1] - b[i - 1][j - 1];
for (int i = 1; i <= n; i ++ )
{
for (int j = 1; j <= m; j ++ )
printf("%d ", b[i][j]);
puts("");
}
return 0;
}