树状数组 算法笔记
liruixiong0101 · · 个人记录
已知一个长度为
- 将某一个数加上
x 。 - 求出某区间的和。
Luogu - P3374 【模板】树状数组 1
对于这个题目,有多种方式求解,例如:
- 暴力求解,时间复杂度
O(mn) 。 - 前缀和求解,由于前缀和不好进行修改,时间复杂度也是
O(mn) 。 - 差分求解,由于需要统计区间和,时间复杂度
O(mn) 。
对于这个题目,我们不好用上述方法求解,我们引入一个新的算法:树状数组。
现在有一个区间
-
-
-
[1+2^{i_0}+2^{i_1},2^{i_0}+2^{i_1}+2^{i_2}]$ 长度为 $2^{i_2} -
\dots
其中
定义
\text{lowbit(3)}=1,\text{lowbit(12)}=4
设上面的区间和为
假设我们可以预处理出区间长度为
于是查询区间
LL query(int x) {
LL ret = 0;
for (int i = x; i; i -= lowbit(i)) {
ret += c[i];
}
return ret;
}
查询区间
然而单点修改
如果将
若要将
代码如下:
void update(int x, int y) {
for (int i = x; i <= n; i += lowbit(i)) {
c[i] += y;
}
}
我们先在就是要求
我们知道负数补码的操作就是将一个数取反后加一,于是就可以简化成这样:
int lowbit(int x) { return x & -x; }
初始化树状数组就是在每一次加入元素中将这个元素加上这个值即可,时间复杂度:
另一种方法就是考虑动态规划加入每一个节点时将其所有的祖宗节点全部加上它的值即可,时间复杂度:
void build() {
for (int i = 1; i <= n; i++) {
c[i] = a[i];
}
for (int i = 1; i <= n; i++) {
if (i + lowbit(i) <= n) {
c[i + lowbit(i)] += c[i];
}
}
}
由于在
所以上面的代码就出来了:
#include <bits/stdc++.h>
using namespace std;
using LL = long long;
const int kMaxN = 5e5 + 5;
int n, m, a[kMaxN], opt, x, y;
LL c[kMaxN];
int lowbit(int x) { return x & -x; }
void update(int x, int y) {
for (int i = x; i <= n; i += lowbit(i)) {
c[i] += y;
}
}
LL query(int x) {
LL ret = 0;
for (int i = x; i; i -= lowbit(i)) {
ret += c[i];
}
return ret;
}
int main() {
ios::sync_with_stdio(0), cin.tie(0);
cin >> n >> m;
for (int i = 1; i <= n; i++) {
cin >> a[i];
update(i, a[i]);
}
while (m--) {
cin >> opt >> x >> y;
if (opt == 1) {
update(x, y);
} else {
cout << query(y) - query(x - 1) << "\n";
}
}
return 0;
}
由此发现,普通树状数组维护的区间必须满足以下特征:
- 结合律:
(x\circ y)\circ z=x\circ(y\circ z) ,其中\circ 是一个二元运算符。 - 可差分:具有逆运算的运算,即已知
x\circ y 和x 可求出y 。
已知一个数列,你需要进行下面两种操作:
- 某区间每一个数加上
x ; - 某一个数的值。
Luogu - P3368 【模板】树状数组 2
这道题考虑用树状数组求解。仔细观察两种操作,第一种操作“每个区间每一个数加上
代码如下:
#include <bits/stdc++.h>
using namespace std;
using LL = long long;
const int kMaxN = 5e5 + 5;
int n, m, a[kMaxN], opt, x, y, k;
LL c[kMaxN];
int lowbit(int x) { return x & -x; }
void update(int x, int y) {
for (int i = x; i <= n; i += lowbit(i)) {
c[i] += y;
}
}
LL query(int x) {
LL ret = 0;
for (int i = x; i; i -= lowbit(i)) {
ret += c[i];
}
return ret;
}
int main() {
ios::sync_with_stdio(0), cin.tie(0);
cin >> n >> m;
for (int i = 1; i <= n; i++) {
cin >> a[i];
update(i, a[i] - a[i - 1]);
}
while (m--) {
cin >> opt;
if (opt == 1) {
cin >> x >> y >> k;
update(x, k), update(y + 1, -k);
} else {
cin >> x;
cout << query(x) << "\n";
}
}
return 0;
}