記錄一下zkw線段樹

    今天重新學習了一下ZKW線段樹,非遞歸版的線段樹。學完之後就是突出一個美麗新世界。

     在這裏用敵兵佈陣測試,並記錄一下方便以後複習。


     

#include<bits/stdc++.h>
using namespace std;
const int maxn = 50005;

int n, N;
int arr[maxn];
int Sum[maxn<<2];

void build(int n){
    memset(Sum, 0, sizeof(Sum));
    N = 1;
    while(N < n+2) N <<= 1;
    for (int i = 1; i <= n; i++)
        Sum[N+i] += arr[i];
    for (int i = N-1; i > 0; i--)
        Sum[i] = Sum[i<<1] + Sum[i<<1|1];
}

void update(int L, int C){
    for (int i = L+N; i > 0; i >>= 1)
        Sum[i] += C;
}

int query(int L, int R){
    int ans = 0;
    int s, t;
    for (s = L+N-1, t = R+N+1; s^t^1; s >>= 1, t >>= 1){
        if (~s&1) ans += Sum[s^1];
        if (t&1) ans += Sum[t^1];
    }
    return ans;
}

int main(){
    std::ios::sync_with_stdio(false);
    int T;
    cin >> T;
    for (int kase = 1; kase <= T; kase++){
        cin >> n;
        for (int i = 1; i <= n; i++)
            cin >> arr[i];
        build(n);

        cout << "Case " << kase << ":" << endl;
        string opt;
        while(cin >> opt){
            if (opt[0] == 'E') break;
            int s, t;
            cin >> s >> t;
            if (opt[0] == 'A') update(s, t);
            if (opt[0] == 'S') update(s, -t);
            if (opt[0] == 'Q') cout << query(s, t) << endl;
        }
    }
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章