70分求调

P3372 【模板】线段树 1

Cockroach_hzs @ 2023-10-18 09:45:11

#include<bits/stdc++.h>
#define lp p<<1
#define rp p<<1|1
#define ll long long
using namespace std;
const int N=1e7;
struct tree{
    ll l,r,lazy,sum;
}tr[4*N];
ll a[N],n,m,a1,b,c,k;
void up(int p){
        tr[p].sum=tr[lp].sum+tr[rp].sum;
    }
void down(int p){
        if(tr[p].lazy){
            tr[lp].sum+=(tr[lp].r-tr[lp].l+1)*tr[p].lazy;
            tr[rp].sum+=(tr[rp].r-tr[rp].l+1)*tr[p].lazy;
            tr[lp].lazy+=tr[p].lazy;
            tr[rp].lazy+=tr[p].lazy;
            tr[p].lazy=0;
        }
    }
void build(int p,int l,int r){
        tr[p]={l,r,0,0};
        if(l==r){
            tr[p].sum=a[l];
            return;
        } 
        int mid=(l+r)>>1;
        build(lp,l,mid);
        build(rp,mid+1,r);
        up(p);
    }
int cha(int p,int l,int r){
        if(l<=tr[p].l&&tr[p].r<=r){
            return tr[p].sum;
        }
        int mid=(tr[p].l+tr[p].r)>>1;
        int sum=0;
        down(p);
        if(l<=mid) sum+=cha(lp,l,r);
        if(r>mid) sum+=cha(rp,l,r);
        return sum;
    }
void change(int p,int l,int r,int v){
        if(l<=tr[p].l&&tr[p].r<=r){
            tr[p].sum+=(tr[p].r-tr[p].l+1)*v;
            tr[p].lazy+=v;
            return;
        }
        int mid=(tr[p].l+tr[p].r)/2;
        down(p);
        if(l<=mid) change(lp,l,r,v);
        if(r>mid) change(rp,l,r,v);
        up(p);
    }
int main(){
    cin>>n>>m;
    for(int i=1;i<=n;i++){
        cin>>a[i];
    }
    build(1,1,n);
    for(int i=1;i<=m;i++){
        cin>>c;
        if(c==1){
            cin>>a1>>b>>k;
            change(1,a1,b,k);
        }
        else{
            int w;
            cin>>a1>>b;
            w=cha(1,a1,b);
            cout<<w<<endl;
        }
    }
    return 0;
}

by hywake @ 2023-10-18 16:00:11

int改long long


|