前缀和 & 差分
前缀和
定义
前缀和可以简单理解为「数列的前
项的和」,是一种重要的预处理方式,能大大降低查询的时间复杂度。
C++ 标准库中实现了前缀和函数 std::partial_sum
,定义于头文件 <numeric>
中。
例题
例题
有
个的正整数放到数组
里,现在要求一个新的数组
,新数组的第
个数
是原数组
第
到第
个数的和。
输入:
输出:
解题思路
递推:B[0] = A[0]
,对于
则 B[i] = B[i-1] + A[i]
。
参考代码
二维/多维前缀和
常见的多维前缀和的求解方法有两种。
基于容斥原理
这种方法多用于二维前缀和的情形。给定大小为
的二维数组
,要求出其前缀和
。那么,
同样是大小为
的二维数组,且

类比一维的情形,
应该可以基于
或
计算,从而避免重复计算前面若干项的和。但是,如果直接将
和
相加,再加上
,会导致重复计算
这一重叠部分的前缀和,所以还需要再将这部分减掉。这就是 容斥原理。由此得到如下递推关系:

实现时,直接遍历
求和即可。
示例
考虑一个具体的例子。

这里,
是给定矩阵
的前缀和。根据定义,
是左图中虚线方框中的子矩阵的和。这里,
是蓝色子矩阵的和,
是红色子矩阵的和,它们重叠部分的和是
。由此可见,如果直接相加
和
,会重复计算
,所以应该有

同样的道理,在已经预处理出二位前缀和后,要查询左上角为
、右下角为
的子矩阵的和,可以计算

这可以在
时间内完成。
在二维的情形,以上算法的时间复杂度可以简单认为是
,即与给定数组的大小成线性关系。但是,当维度
增大时,由于容斥原理涉及的项数以指数级的速度增长,时间复杂度会成为
,这里
是数组维度,而
是给定数组大小。因此,该算法不再适用。
洛谷 P1387 最大正方形
在一个
的只包含
和
的矩阵里找出一个不包含
的最大正方形,输出边长。
参考代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35 | #include <algorithm>
#include <iostream>
using namespace std;
int a[103][103];
int b[103][103]; // 前缀和数组,相当于上文的 sum[]
int main() {
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> a[i][j];
b[i][j] =
b[i][j - 1] + b[i - 1][j] - b[i - 1][j - 1] + a[i][j]; // 求前缀和
}
}
int ans = 0;
int l = 1;
while (l <= min(n, m)) { // 判断条件
for (int i = l; i <= n; i++) {
for (int j = l; j <= m; j++) {
if (b[i][j] - b[i - l][j] - b[i][j - l] + b[i - l][j - l] == l * l) {
ans = max(ans, l); // 在这里统计答案
}
}
}
l++;
}
cout << ans << endl;
return 0;
}
|
| n, m = map(int, input().split())
a = [list(map(int, input().split())) for _ in range(n)]
b = [a[0]] + [[i[0]] + [0] * (m - 1) for i in a[1:]]
ans = 0
for i in range(1, n):
for j in range(1, m):
if a[i][j]:
b[i][j] = min(b[i - 1][j], b[i][j - 1], b[i - 1][j - 1]) + 1
ans = max(ans, b[i][j])
print(ans)
|
逐维前缀和
对于一般的情形,给定
维数组
,大小为
,同样要求得其前缀和
。这里,

从上式可以看出,
维前缀和就等于
次求和。所以,一个显然的算法是,每次只考虑一个维度,固定所有其它维度,然后求若干个一维前缀和,这样对所有
个维度分别求和之后,得到的就是
维前缀和。
三维前缀和的参考实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44 | #include <iostream>
#include <vector>
int main() {
// Input.
int N1, N2, N3;
std::cin >> N1 >> N2 >> N3;
std::vector<std::vector<std::vector<int>>> a(
N1 + 1, std::vector<std::vector<int>>(N2 + 1, std::vector<int>(N3 + 1)));
for (int i = 1; i <= N1; ++i)
for (int j = 1; j <= N2; ++j)
for (int k = 1; k <= N3; ++k) std::cin >> a[i][j][k];
// Copy.
auto ps = a;
// Prefix-sum for 3rd dimension.
for (int i = 1; i <= N1; ++i)
for (int j = 1; j <= N2; ++j)
for (int k = 1; k <= N3; ++k) ps[i][j][k] += ps[i][j][k - 1];
// Prefix-sum for 2nd dimension.
for (int i = 1; i <= N1; ++i)
for (int j = 1; j <= N2; ++j)
for (int k = 1; k <= N3; ++k) ps[i][j][k] += ps[i][j - 1][k];
// Prefix-sum for 1st dimension.
for (int i = 1; i <= N1; ++i)
for (int j = 1; j <= N2; ++j)
for (int k = 1; k <= N3; ++k) ps[i][j][k] += ps[i - 1][j][k];
// Output.
for (int i = 1; i <= N1; ++i) {
for (int j = 1; j <= N2; ++j) {
for (int k = 1; k <= N3; ++k) {
std::cout << ps[i][j][k] << ' ';
}
std::cout << '\n';
}
std::cout << '\n';
}
return 0;
}
|
因为考虑每一个维度的时候,都只遍历了整个数组一遍,这样的算法复杂度是
的,通常可以接受。
特例:子集和 DP
维度比较大的情形,经常出现在一类叫做 子集和 (SOS, Sum Over Subsets) 的问题中。这是高维前缀和的特例。
问题描述如下。考虑大小为
的集合的全体子集上面定义的函数
,现在要求出其子集和函数
,它满足

即
等于其所有子集
上的函数值
的和。
首先,子集和问题可以写成高维前缀和的形式。注意到,子集
可以通过状态压缩的思想表示为长度为
的 0-1 字符串
。将字符串的每一位都看作是数组下标的一个维度,那么
其实就是一个
维数组,且每个维度下标都一定在
之间。同时,子集的包含关系就等价于下标的大小关系,即

所以,对子集求和,就是求这个
维数组的前缀和。
现在,可以直接使用前文所述的逐维前缀和的方法求得子集和。时间复杂度是
。
参考实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26 | #include <iostream>
#include <vector>
int main() {
int n;
std::cin >> n;
std::vector<int> a(1 << n);
for (int& x : a) std::cin >> x;
// Copy.
auto ps = a;
// Loop over dimensions.
for (int i = 0; i < n; ++i) {
// Loop over i-th dimension.
for (int st = 0; st < (1 << n); ++st) {
// This condition implies that i-th dimension is 1.
if ((st >> i) & 1) {
// ps[... 1 ...] += ps[... 0 ...]. (i-th dimension)
ps[st] += ps[st ^ (1 << i)];
}
}
}
for (int x : ps) std::cout << x << ' ';
return 0;
}
|
子集和的逆操作需要通过 容斥原理 进行。子集和问题也是快速莫比乌斯变换的必要步骤之一。
树上前缀和
设
表示结点
到根节点的权值总和。
然后:
差分
解释
差分是一种和前缀和相对的策略,可以当做是求和的逆运算。
这种策略的定义是令 ![b_i=\begin{cases}a_i-a_{i-1}\,&i \in[2,n] \\ a_1\,&i=1\end{cases}](data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)
性质
它可以维护多次对序列的一个区间加上一个数,并在最后询问某一位的数或是多次询问某一位的数。注意修改操作一定要在查询操作之前。
示例
譬如使
中的每个数加上一个
,即
其中
,
最后做一遍前缀和就好了。
C++ 标准库中实现了差分函数 std::adjacent_difference
,定义于头文件 <numeric>
中。
树上差分
树上差分可以理解为对树上的某一段路径进行差分操作,这里的路径可以类比一维数组的区间进行理解。例如在对树上的一些路径进行频繁操作,并且询问某条边或者某个点在经过操作后的值的时候,就可以运用树上差分思想了。
树上差分通常会结合 树基础 和 最近公共祖先 来进行考察。树上差分又分为 点差分 与 边差分,在实现上会稍有不同。
点差分
举例:对树上的一些路径
进行访问,问一条路径
上的点被访问的次数。
对于一次
的访问,需要找到
与
的公共祖先,然后对这条路径上的点进行访问(点的权值加一),若采用 DFS 算法对每个点进行访问,由于有太多的路径需要访问,时间上承受不了。这里进行差分操作:

其中
表示
的父亲节点,
为点权
的差分数组。

可以认为公式中的前两条是对蓝色方框内的路径进行操作,后两条是对红色方框内的路径进行操作。不妨令
左侧的直系子节点为
。那么有
,
。可以发现实际上点差分的操作和上文一维数组的差分操作是类似的。
边差分
若是对路径中的边进行访问,就需要采用边差分策略了,使用以下公式:


由于在边上直接进行差分比较困难,所以将本来应当累加到红色边上的值向下移动到附近的点里,那么操作起来也就方便了。对于公式,有了点差分的理解基础后也不难推导,同样是对两段区间进行差分。
例题
洛谷 3128 最大流
FJ 给他的牛棚的
个隔间之间安装了
根管道,隔间编号从
到
。所有隔间都被管道连通了。
FJ 有
条运输牛奶的路线,第
条路线从隔间
运输到隔间
。一条运输路线会给它的两个端点处的隔间以及中间途径的所有隔间带来一个单位的运输压力,你需要计算压力最大的隔间的压力是多少。
解题思路
需要统计每个点经过了多少次,那么就用树上差分将每一次的路径上的点加一,可以很快得到每个点经过的次数。这里采用倍增法计算 LCA,最后对 DFS 遍历整棵树,在回溯时对差分数组求和就能求得答案了。
参考代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78 | #include <algorithm>
#include <iostream>
using namespace std;
constexpr int MAXN = 50010;
struct node {
int to, next;
} edge[MAXN << 1];
int fa[MAXN][30], head[MAXN << 1];
int power[MAXN];
int depth[MAXN], lg[MAXN];
int n, k, ans = 0, tot = 0;
void add(int x, int y) { // 加边
edge[++tot].to = y;
edge[tot].next = head[x];
head[x] = tot;
}
void dfs(int now, int father) { // dfs求最大压力
fa[now][0] = father;
depth[now] = depth[father] + 1;
for (int i = 1; i <= lg[depth[now]]; ++i)
fa[now][i] = fa[fa[now][i - 1]][i - 1];
for (int i = head[now]; i; i = edge[i].next)
if (edge[i].to != father) dfs(edge[i].to, now);
}
int lca(int x, int y) { // 求LCA,最近公共祖先
if (depth[x] < depth[y]) swap(x, y);
while (depth[x] > depth[y]) x = fa[x][lg[depth[x] - depth[y]] - 1];
if (x == y) return x;
for (int k = lg[depth[x]] - 1; k >= 0; k--) {
if (fa[x][k] != fa[y][k]) x = fa[x][k], y = fa[y][k];
}
return fa[x][0];
}
// 用dfs求最大压力,回溯时将子树的权值加上
void get_ans(int u, int father) {
for (int i = head[u]; i; i = edge[i].next) {
int to = edge[i].to;
if (to == father) continue;
get_ans(to, u);
power[u] += power[to];
}
ans = max(ans, power[u]);
}
int main() {
cin.tie(nullptr)->sync_with_stdio(false);
cin >> n >> k;
int x, y;
for (int i = 1; i <= n; i++) {
lg[i] = lg[i - 1] + (1 << lg[i - 1] == i);
}
for (int i = 1; i <= n - 1; i++) { // 建图
cin >> x >> y;
add(x, y);
add(y, x);
}
dfs(1, 0);
int s, t;
for (int i = 1; i <= k; i++) {
cin >> s >> t;
int ancestor = lca(s, t);
// 树上差分
power[s]++;
power[t]++;
power[ancestor]--;
power[fa[ancestor][0]]--;
}
get_ans(1, 0);
cout << ans << '\n';
return 0;
}
|
习题
前缀和:
二维/多维前缀和:
树上前缀和:
差分:
树上差分:
参考资料与注释
本页面最近更新:2024/9/29 19:42:16,更新历史
发现错误?想一起完善? 在 GitHub 上编辑此页!
本页面贡献者:ChungZH, H-J-Granger, NachtgeistW, Alpacabla, Alpha1022, Backl1ght, c-forrest, Chrogeek, countercurrent-time, diauweb, Enter-tainer, Henry-ZHR, iamtwz, Ir1d, Junyan721113, kenlig, Kensuke-Hinata, ksyx, LeiJinpeng, LeoJacob, leoleoasd, mgt, ouuan, Planet6174, ShaoChenHeng, shawlleyw, sshwy, SukkaW, Tiphereth-A, wuyudi
本页面的全部内容在 CC BY-SA 4.0 和 SATA 协议之条款下提供,附加条款亦可能应用