41 lines
1000 B
Markdown
41 lines
1000 B
Markdown
|
|
## [$P3374$ 【模板】树状数组 1](https://www.luogu.com.cn/problem/P3374)
|
|||
|
|
|
|||
|
|
```cpp {.line-numbers}
|
|||
|
|
#include <bits/stdc++.h>
|
|||
|
|
|
|||
|
|
using namespace std;
|
|||
|
|
typedef long long LL;
|
|||
|
|
const int N = 5 * 1e5 + 10;
|
|||
|
|
int n, m;
|
|||
|
|
int a[N];
|
|||
|
|
|
|||
|
|
// 树状数组模板
|
|||
|
|
// 用while循环优于for循环,因为没有i变量,不易写错,代码更短
|
|||
|
|
#define lowbit(x) (x & -x)
|
|||
|
|
int c[N];
|
|||
|
|
void add(int x, int v) {
|
|||
|
|
while (x < N) c[x] += v, x += lowbit(x);
|
|||
|
|
}
|
|||
|
|
LL sum(int x) {
|
|||
|
|
LL res = 0;
|
|||
|
|
while (x) res += c[x], x -= lowbit(x);
|
|||
|
|
return res;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
int main() {
|
|||
|
|
cin >> n >> m;
|
|||
|
|
for (int i = 1; i <= n; i++)
|
|||
|
|
cin >> a[i], add(i, a[i]); // 维护进入树状数组,两个概念:位置,值
|
|||
|
|
|
|||
|
|
while (m--) {
|
|||
|
|
int op, x, y;
|
|||
|
|
cin >> op >> x >> y;
|
|||
|
|
if (op == 1)
|
|||
|
|
add(x, y); // 在x位置上加上y
|
|||
|
|
else
|
|||
|
|
// 计算[x,y]之间的数字和
|
|||
|
|
cout << sum(y) - sum(x - 1) << endl;
|
|||
|
|
}
|
|||
|
|
return 0;
|
|||
|
|
}
|
|||
|
|
```
|