【模板】树状数组 1
https://www.luogu.com.cn/problem/P3374
题目描述
如题,已知一个数列,你需要进行下面两种操作:
-
将某一个数加上 xxx
-
求出某区间每一个数的和
输入格式
第一行包含两个正整数 n,mn,mn,m,分别表示该数列数字的个数和操作的总个数。
第二行包含 nnn 个用空格分隔的整数,其中第 iii 个数字表示数列第 iii 项的初始值。
接下来 mmm 行每行包含 333 个整数,表示一个操作,具体如下:
-
1 x k
含义:将第 xxx 个数加上 kkk -
2 x y
含义:输出区间 [x,y][x,y][x,y] 内每个数的和
输出格式
输出包含若干行整数,即为所有操作 222 的结果。
样例 #1
样例输入 #1
5 5
1 5 4 2 3
1 1 3
2 2 5
1 3 -1
1 4 2
2 1 4
样例输出 #1
14
16
提示
【数据范围】
对于 30%30\%30% 的数据,1≤n≤81 \le n \le 81≤n≤8,1≤m≤101\le m \le 101≤m≤10;
对于 70%70\%70% 的数据,1≤n,m≤1041\le n,m \le 10^41≤n,m≤104;
对于 100%100\%100% 的数据,1≤n,m≤5×1051\le n,m \le 5\times 10^51≤n,m≤5×105。
数据保证对于任意时刻,aaa 的任意子区间(包括长度为 111 和 nnn 的子区间)和均在 [−231,231)[-2^{31}, 2^{31})[−231,231) 范围内。
样例说明:
故输出结果14、16
代码
#include <bits/stdc++.h>
#define endl "\n"
using namespace std;
int lowbit(const int &n) {
return n & (-n);
}
int getSum(const vector<int> &BIT, int x) { // 求前x项和
int result = 0;
while (x) {
result += BIT[x];
x -= lowbit(x);
}
return result;
}
// 树状数组某一位加上数字
void updateBIT(vector<int> &BIT, int index, int value) {
while (index < BIT.size()) {
BIT[index] += value;
index += lowbit(index);
}
}
// 构建树状数组
void constructBIT(const vector<int> &originArr, vector<int> &BIT) {
for (size_t i = 0; i < originArr.size(); i++) {
updateBIT(BIT, i + 1, originArr[i]);
}
}
void solve() {
int n, m; // n为数列数字的个数,m为操作的总个数
cin >> n >> m;
vector<int> originArr(n); // 输入原始数组
for (int i = 0; i < n; i++) {
cin >> originArr[i];
}
vector<int> BIT(n + 1, 0); // 树状数组
constructBIT(originArr, BIT); // 构建树状数组
while (m--) { // m次操作
int op, x, y;
cin >> op >> x >> y;
if (op == 1) {
updateBIT(BIT, x, y);
} else {
cout << getSum(BIT, y) - getSum(BIT, x - 1) << endl;
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
solve();
return 0;
}
树状数组
的基础用法