树状数组
#include <iostream>
using namespace std;
const int N = 1E5 + 10;
int tr[N];
int lowbit(int x){
return x & -x;
}
void add(int index, int x){
for(int i = index; i < N; i += lowbit(i)) tr[i] += x;
}
int query(int index){
int sum = 0;
for(int i = index; i ; i -= lowbit(i)) sum += tr[i];
return sum;
}
int main(){
int n, m; cin >> n >> m;
for(int i = 1; i <= n; i ++ ){
int tmp; cin >> tmp;
add(i, tmp);
}
while(m -- ){
int k, a, b; cin >> k >> a >> b;
if(k) add(a, b);
else cout << query(b) - query(a - 1) << endl;
}
return 0;
}
线段树
#include <iostream>
#include <cstdio>
using namespace std;
const int N = 1E5 + 10;
struct node{
int l, r;
int sum;
}tr[N * 4];
int w[N];
void pushup(int u){
tr[u].sum = tr[u << 1].sum + tr[u << 1 | 1].sum;
}
void build(int u, int l, int r){
if(l == r) tr[u] = {l, r, w[l]};
else{
tr[u] = {l, r};
int mid = l + r >> 1;
build(u << 1, l, mid);
build(u << 1 | 1, mid + 1, r);
pushup(u);
}
}
void modify(int u, int index, int x){
if(tr[u].l == tr[u].r) tr[u].sum += x;
else{
int mid = tr[u].l + tr[u].r >> 1;
if(index <= mid) modify(u << 1, index, x);
else modify(u << 1 | 1, index, x);
pushup(u);
}
}
int query(int u, int l, int r){
if(tr[u].l >= l && tr[u].r <= r) return tr[u].sum;
int mid = tr[u].l + tr[u].r >> 1;
int sum = 0;
if(l <= mid) sum += query(u << 1, l, r);
if(r > mid) sum += query(u << 1 | 1, l, r);
return sum;
}
int main(){
int n, m; cin >> n >> m;
for(int i = 1; i <= n; i ++ ) scanf("%d", &w[i]);
build(1, 1, n);
while(m -- ){
int k, a, b; scanf("%d%d%d", &k, &a, &b);
if(k) modify(1, a, b);
else cout << query(1, a, b) << endl;
}
return 0;
}