板子求调

P3372 【模板】线段树 1

ragwort @ 2023-02-15 23:01:32

#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 1e5+10;

int t[N*4],a[N],n,m;

inline void build(int k,int l,int r){
    if(l == r){
        t[k] = a[l];
        return ;
    }

    int mid = l + r >> 1;
    build(k*2,l,mid);
    build(k*2+1,mid+1,r);

    t[k] = t[k*2]+t[k*2+1];
}

inline void update(int k,int l,int r,int v){
    if(l == r){
        t[k] += v;
        return ;
    }

    int mid = l + r >> 1;
    update(k*2,l,mid,v);
    update(k*2+1,mid+1,r,v);

    t[k] = t[k*2] + t[k*2+1];
}

inline int query(int k,int l,int r,int x,int y){
    if(x <= l && y >= r) return t[k];

    int mid = l+r>>1,res=0;
    if(x <= mid) res = query(k*2,l,mid,x,y);
    if(y > mid) res += query(k*2+1,mid+1,r,x,y);

    return res;
}

signed main() {

    cin >> n >> m;

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

    int x,y,z;
    while(m--){
        cin >> x;
        if(x == 2){
            cin >> x >> y;
            cout << query(1,1,n,x,y) << endl;
        }else{
            cin >> x >> y >> z;
            update(1,x,y,z);
        }
    }

    return 0;
}

谢谢


by Placy @ 2023-02-16 06:33:12

懒得写的话用树状数组混过去也行


上一页 |