版本比较
树状数组
正文
增加 29 行删除 18 行
185 行未改动全部展开1861871881891901911921901911941951961971981992002012021921931941951961971981992002012022032042052062072082092102042112122132142152162172182092102192202212222132232242252152162262272282292302317 行未改动185 行未改动全部展开```cpp#include <bits/stdc++.h>using namespace std;
const int N = 500005;int n, m;int tr[N];using T = int;
int lowbit(int x) { return x & -x; }
void add(int i, int v) { for(; i <= n; i += lowbit(i)) tr[i] += v;}
int query(int i) { int res = 0; for(; i; i -= lowbit(i)) res += tr[i];struct Fenwick { int n; vector<T> tr; Fenwick(int n) {init(n);} void init(int _n){ n=_n; tr.assign(n+1,0); } void add(int x, T c){ for(; x <= n; x += x&-x) { tr[x]+=c; } } T sum(int x){ T res=0; for(; x; x -= x&-x) { res+=tr[x]; } return res;} }};
int main() { int n,m; cin >> n >> m; Fenwick bit(n); // 实例化一个新的树状数组 for(int i = 1; i <= n; i++) { int x; cin >> x; add(i, x); // 初始化:逐个插入 T x; cin >> x; bit.add(i, x); // 初始化:逐个插入 } while(m--) { int op, x, y; int op; T x, y; cin >> op >> x >> y; if(op == 1) add(x, y); // 单点修改 else cout << query(y) - query(x - 1) << '\n'; // 区间查询 if(op == 1) bit.add(x, y); // 单点修改 else cout << bit.sum(y) - bit.sum(x - 1) << '\n'; // 区间查询 } return 0; // 完结散花!}```7 行未改动