树状数组模板

· · 个人记录

#include<bits/stdc++.h>
using namespace std;
int c[500005],a[5000005],n,m;int x,y,z;
int low(int x) {return x&(-x);}
int get(int x){//求和
    int ans=0;
    while(x>0){
        ans+=c[x];
        x-=low(x);
    }
    return ans;
}
void u(int x,int v){//修改树的值
    a[x]+=v;
    while(x<=n){
        c[x]+=v;
        x+=low(x);
    }
}
signed main(){
    cin>>n>>m;
    std::ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
    for(int i=1;i<=n;i++) cin>>a[i],u(i,a[i]); 
    for(int i=1;i<=m;i++){
        cin>>x>>y>>z;
        if(x==1){u(y,z);}
        if(x==2){
            cout<<get(z)-get(y-1)<<"\n";
        }

    }
    return 0;
}