线段树区间和,区间修改,区间查询板子

#include <bits/stdc++.h>

using namespace std;

using LL = long long;

#define lson (nd<<1)
#define rson (nd<<1|1)
#define mid (l+r>>1)

const int N = 1e5+5;

int sum[N<<2], lazy[N<<2];

int a[N];

void build(int nd, int l, int r){
    if(l==r){
        sum[nd]=a[l];
        return;
    }

    build(lson, l, mid);
    build(rson, mid+1, r);
    sum[nd] += sum[lson] + sum[rson];
}


void push_down(int nd, int l, int r){
    if(lazy[nd]){
        lazy[lson] += lazy[nd];
        lazy[rson] += lazy[nd];
        sum[lson] += (mid-l+1) * lazy[nd];
        sum[rson] += (r-mid) * lazy[nd];
        lazy[nd] = 0;
    }
}

void update(int nd, int l, int r, int L, int R, int val){
    if(L<=l&&R>=r){
        sum[nd] += (r-l+1) * val;
        lazy[nd] += val;
        return;
    }
    push_down(nd, l, r);
    if(L<=mid){
        update(lson, l, mid, L, R, val);
    }
    if(R>mid){
        update(rson, mid+1, r, L, R, val);
    }

    sum[nd] = sum[lson] + sum[rson];
}

int query(int nd, int l, int r, int L, int R){
    if(l>=L&&R>=r){
        return sum[nd];
    }
    push_down(nd, l, r);
    int ret=0;
    if(L<=mid){
        ret+=query(lson, l, mid, L, R);
    }
    if(R>mid){
        ret+=query(rson, mid+1, r, L, R);
    }

    return ret;
}

int n;

int main(){
    cin >> n;
    for(int i=1;i<=n;++i){
        cin >> a[i];
    }

    build(1, 1, n);
    update(1, 1, n, 1, 3, -1);
    update(1, 1, n, 2, 5, 1);
    
    return 0;
}
posted @ 2023-04-12 18:26  John_Ran  阅读(13)  评论(0编辑  收藏  举报