Files
python/TangDou/AcWing/BIT/P3368.md
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

107 lines
2.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

##[$P3368$ 【模板】树状数组 $2$](https://www.luogu.com.cn/problem/P3368)
* 知识点:**区间修改,单点查询**
通过 **差分**(就是记录数组中每个元素与前一个元素的差),可以把这个问题转化为问题 **单点修改,区间查询**
#### 查询
设原数组为$a[i]$, 设数组$b[i]=a[i]-a[i-1](a[0]=0)$,则$\displaystyle a[i]=\sum_{j=1}^{i}b[j]$,可以通过求$b[i]$的前缀和查询。
#### 修改
当给区间$[l,r]$加上$x$的时候,$a[l]$与前一个元素 $a[l-1]$的差增加了$x$,$a[r+1]$与 $a[r]$的差减少了$x$。根据$b[i]$数组的定义,只需给$a[l]$加上$x$, 给 $a[r+1]$减去$x$即可。
```cpp {.line-numbers}
#include <bits/stdc++.h>
using namespace std;
const int N = 5e5 + 10;
int a[N]; // a是原数组。t是差分数组,用树状数组维护
int n, m;
// 树状数组模板
#define lowbit(x) (x & -x)
int c[N];
void add(int x, int v) {
while (x < N) c[x] += v, x += lowbit(x);
}
int sum(int x) {
int res = 0;
while (x) res += c[x], x -= lowbit(x);
return res;
}
int main() {
scanf("%d %d", &n, &m);
// 原数组
for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
int op, l, r, v, k;
while (m--) {
scanf("%d", &op);
if (op == 1) {
scanf("%d %d %d", &l, &r, &v);
add(l, v), add(r + 1, -v);
} else {
scanf("%d", &k);
// 树状数组维护的是变化量,还需要加上原来的值
printf("%d\n", a[k] + sum(k)); // 求某点的值
}
}
return 0;
}
```
也可以这样:
```cpp {.line-numbers}
#include <bits/stdc++.h>
using namespace std;
const int N = 5e5 + 10;
int a[N]; // a是原数组。c是差分数组,用树状数组维护
int n, m;
// 树状数组模板
#define lowbit(x) (x & -x)
int c[N];
void add(int x, int v) {
while (x < N) c[x] += v, x += lowbit(x);
}
int sum(int x) {
int res = 0;
while (x) res += c[x], x -= lowbit(x);
return res;
}
int main() {
#ifndef ONLINE_JUDGE
freopen("P3368.in", "r", stdin);
#endif
scanf("%d %d", &n, &m);
// 原数组
for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
// 保存差分数组
for (int i = 1; i <= n; i++) add(i, a[i] - a[i - 1]);
int op, l, r, v, k;
while (m--) {
scanf("%d", &op);
if (op == 1) {
scanf("%d %d %d", &l, &r, &v);
add(l, v), add(r + 1, -v);
} else {
scanf("%d", &k);
// 树状数组维护的是变化量,还需要加上原来的值
printf("%d\n", sum(k)); // 求某点的值
}
}
return 0;
}
```