C ++ツリー配列の単純なテンプレート

#include <iostream>
#include <cstdio>

using namespace std;

const int N = 100010;

int a[N], tr[N];
int n, m;

//lowbit 函数
int lowbit(int x){
    
    
    return x & -x;
}

//在第x的数上加上v
void add(int x, int v){
    
    
    for(int i = x; i <= n; i += lowbit(i)){
    
    
        tr[i] += v;
    }
}

//求第1到第x个数之间的所有数之和
int query(int x){
    
    
    int res = 0;
    for(int i = x; i; i -= lowbit(i)){
    
    
        res += tr[i];
    }
    return res;
}

int main(){
    
    
    ios::sync_with_stdio(false);
    cin.tie(0);

    cin >> n >> m;

    for(int i = 1; i <=n; i ++) cin >> a[i];
    for(int i = 1; i <=n; i ++) add(i,a[i]);

    while(m --){
    
    
        int k, x, y;
        cin >> k >> x >> y;
        if(k == 0) cout<< query(y) - query(x - 1) << endl;
        else add(x, y);
    }

    return 0;
}

おすすめ

転載: blog.csdn.net/qq_43663263/article/details/109300933