P3374 【模板】树状数组 1

#include<bits/stdc++.h>
using namespace std;
const int maxn=5*1e5+5;
int tree[maxn];
int n,m,op,a,k;
int lowbit(int x){
    return x&(-x);
}
void add(int x,int k){
    while(x<=n){
        tree[x]+=k;
        x+=lowbit(x);
    }
}
int sum(int x){
    int ans=0;
    while(x!=0){
        ans+=tree[x];
        x-=lowbit(x);
    }
    return ans;
}

int main()
{
    cin>>n>>m;
    for(int i=1;i<=n;i++){
        scanf("%d",&a);
        add(i,a);
    }

    for(int i=0;i<m;i++){
        cin>>op;
        if(op==1){
            scanf("%d%d",&a,&k);
            add(a,k);
        }
        else{
            scanf("%d%d",&a,&k);
            cout<<sum(k)-sum(a-1)<<endl;
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/mohari/p/12933349.html