前缀和学完了,与前缀和相对应的就是差分,差分是前缀和的逆运算,比如一个数组 a,差分数组是 b,那么 a 就是 b 的前缀和数组,也可以理解为,a[i] = b[1] + …b[i]。
如果得到差分数组呢,类似高中学过的叠加法逆运算,比如:
b[1] = a[1] - a[0];
b[2] = a[2] - a[1];
.
.
.
.
b[i] = a[i] - a[i - 1];
将 b 数组累加,就会发现结果得,a[i] - a[0] 由于 a[0] 等于 0,所以 a 是 b 数组的前缀和。
差分数组的作用:
有一种情况,非常试用,比如 将数组 a 的 [l, r] 这一区间加上一个常数 c,最暴力的做法就是 for 循环加,但是这样的复杂度有点高,所以换一种思路。
假如说 i 等于 2,如果让 b[2] 加上 一个常数 c,对于 b 数组来说,只有 b[2] 变了,但是对于 a 数组来说,是 a[2] 以后的所有数字都加上了常数 c。
同理如果求得是一个区间,那么我们只需要让 b[r + 1] 的值 减去 c,这样加 c 减 c,值就不变了,但是 l - r 区间的值都加上了 c
从 l 开始的每一个数都加上 c,从 r + 1 开始的每一个数都减去 c,相当于 r + 1 后面的数不变,但是区间部分加上 c
理论完毕,接下来是一个小练习:
https://www.acwing.com/problem/content/description/799/
思路上面都有,就不写注释了
#include<iostream>
#include<string>
#include<algorithm>
#include<bits/stdc++.h>
#include<stack>
#include<set>
#include<vector>
#include<map>
#include<queue>
#include<deque>
#include<cctype>
#include<unordered_set>
#include<unordered_map>
#include<fstream>
#include<cstring>
using namespace std;
const int N = 100001;
int a[N], b[N];
int main() {
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++) {
cin >> a[i];
b[i] = a[i] - a[i - 1];
}
while (m--) {
int l, r, c;
cin >> l >> r >> c;
b[l] += c;
b[r + 1] -= c;
}
for (int i = 1; i <= n; i++) {
b[i] += b[i - 1];
cout << b[i] << " ";
}
}
二维数组的差分:
从本图,如果想让 矩阵 x1, y1 到 x2, y2 的和加上一个常数 c,只需要让:
b[x1][y1] + c
b[x1[y2 + 1] - c
b[x2 + 1][y1] - c
b[x2 + 1][y2 + 1] + c
类似前缀和的二分:
例题:
这里比较复杂,我解释一下
要想真正理解差分的二维方法,需要画图来辅助思维:
要想让 矩阵 x1, y1 -> x2 y2 的值加上一个常量,我们只需要,找出 图中蓝色的三个点,然后让
b[x1][y1] + c
b[x1[y2 + 1] - c
b[x2 + 1][y1] - c
b[x2 + 1][y2 + 1] + c
在做初始化的时候,如图:
或者 : b[i][j] = a[i][j] - a[i - 1][j] - a[i][j - 1] + a[i - 1][j - 1]
#include<iostream>
#include<string>
#include<algorithm>
#include<bits/stdc++.h>
#include<stack>
#include<set>
#include<vector>
#include<map>
#include<queue>
#include<deque>
#include<cctype>
#include<unordered_set>
#include<unordered_map>
#include<fstream>
#include<cstring>
using namespace std;
const int N = 1001;
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() {
int n, m, q;
cin >> n >> m >> q;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> a[i][j];
insert(i, j, i, j, a[i][j]);// 求查分数组 b
}
}
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];// 求前缀和,得出的结果就是 a 矩阵变化后的结果
}
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (j == 1) {
cout << b[i][j];
} else {
cout << " " << b[i][j];
}
}
cout << endl;
}
}
/**
3 4 3
1 2 2 1
3 2 2 1
1 1 1 1
1 1 2 2 1
1 3 2 3 2
3 1 3 4 1
**/