刚学线段树,求调

P3372 【模板】线段树 1

miffy_123 @ 2024-03-13 21:01:04

#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define INF 2147483646
#define inf 9223372036854775806
#define pl putchar('\n');
const ll mxn=100005;
struct lt{
    ll l,r,sum;
    ll lazy_tag;
}t[4*mxn]; 
ll a[mxn];
void build(ll p,ll l,ll r){
    t[p].l=l;
    t[p].r=r;
    if(l==r){
        t[p].sum=a[l];
        return;
    }
    ll mid=(l+r)/2;
    build(p*2,l,mid);
    build(p*2+1,mid+1,r);
    t[p].sum=t[p*2].sum+t[p*2+1].sum;
    return;
}
void change(ll p,ll l,ll r,ll v){
    if(t[p].l>r||t[p].r<l){
        return;
    }
    if(l<=t[p].l&&r>=t[p].r){
        t[p].sum+=(t[p].r-t[p].l+1)*t[p].lazy_tag;
        t[p].lazy_tag+=v;
        return;
    }
    if(t[p].lazy_tag!=0){
        t[p*2].sum+=(t[p*2].r-t[p*2].l+1)*t[p].lazy_tag;
        t[p*2+1].sum+=(t[p*2+1].r-t[p*2+1].l+1)*t[p].lazy_tag;
        t[p*2].lazy_tag+=t[p].lazy_tag;
        t[p*2+1].lazy_tag+=t[p].lazy_tag;
        t[p].lazy_tag=0;
    }
    ll mid=(t[p].l+t[p].r)/2;
    if(mid>=l){
        change(p*2,l,r,v);
    }
    if(mid<=r){
        change(p*2+1,l,r,v);
    }
    t[p].sum=t[p*2].sum+t[p*2+1].sum;
    return;
}
ll ask(ll p,ll l,ll r){
    if(t[p].l>r||t[p].r<l){
        return 0;
    }
    if(l<=t[p].l&&r>=t[p].r){
        return t[p].sum;
    }
    if(t[p].lazy_tag!=0){
        t[p*2].sum+=(t[p*2].r-t[p*2].l+1)*t[p].lazy_tag;
        t[p*2+1].sum+=(t[p*2+1].r-t[p*2+1].l+1)*t[p].lazy_tag;
        t[p*2].lazy_tag+=t[p].lazy_tag;
        t[p*2+1].lazy_tag+=t[p].lazy_tag;
        t[p].lazy_tag=0;
    }
    ll mid=(t[p].l+t[p].r)/2;
    ll ret=0;
    if(mid>=l){
        ret+=ask(p*2,l,r);
    }
    if(mid<r){
        ret+=ask(p*2+1,l,r);
    }
    return ret;
}
ll n,m;
int main(){
    cin>>n>>m;
    for(ll i=1;i<=n;i++){
        cin>>a[i];
    } 
    build(1,1,n);
    while(m--){
        ll opt;
        cin>>opt;
        if(opt==1){
            ll x,y,k;
            cin>>x>>y>>k;
            change(1,x,y,k);
        }
        else{
            ll x,y;
            cin>>x>>y;
            cout<<ask(1,x,y)<<endl;
        }
    }
    return 0;
}

by miffy_123 @ 2024-03-13 21:05:56

@HuYangMu2011


by long_ting @ 2024-03-14 09:42:36


if(l<=t[p].l&&r>=t[p].r){
        t[p].sum+=(t[p].r-t[p].l+1)*t[p].lazy_tag;
        t[p].lazy_tag+=v;
        return;
    }

改为

t[p].sum+=(t[p].r-t[p].l+1)*v;

by long_ting @ 2024-03-14 09:42:44

@long_ting


by long_ting @ 2024-03-14 09:42:54

@miffy_123


by miffy_123 @ 2024-03-14 21:19:00

蟹蟹大佬,已关


|