线段树0分求助,全WA

P3372 【模板】线段树 1

LLX7 @ 2024-11-16 14:30:48


#include<bits/stdc++.h>
#define int long long 
using namespace std;
const int N=5e5;
int w[N];
struct edge{
    int l,r,sum,add;
}tr[4*N];
void pushup(int p){
    tr[p].sum=tr[p*2].sum+tr[p*2+1].sum;
}
void pushdown(int p){
    if(tr[p].add){
        tr[p].add=0;
        tr[p*2].sum+=tr[p].add*(tr[p*2].r-tr[p*2].l+1);
        tr[p*2+1].sum+=tr[p].add*(tr[p*2+1].r-tr[p*2+1].l+1);
        tr[p*2].add+=tr[p].add;
        tr[p*2+1].add+=tr[p].add;
    }
}
void build(int p,int l,int r){
    tr[p].l=l,tr[p].r=r;
    if(l==r){
        tr[p].sum=w[l];
        return ;
    }
    int mid=l+r>>1;
    build(p*2,l,mid);
    build(p*2+1,mid+1,r);
    pushup(p);
}
void updata(int p,int x,int y,int k){
    if(tr[p].l>=x&&tr[p].r<=y){
        tr[p].add+=k;
        tr[p].sum+=(tr[p].r-tr[p].l+1)*k;
        return ;
    }
    int mid=tr[p].l+tr[p].r>>1;
    pushdown(p);
    if(x<=mid){
        updata(p*2,x,y,k);
    }
    if(y>mid){
        updata(p*2+1,x,y,k);
    }
    pushup(p);
}
int query(int p,int x,int y){
    if(tr[p].l>=x&&tr[p].r<=y){
        return tr[p].sum;
    }
    int mid=(tr[p].l+tr[p].r)>>1,sum=0;
    pushdown(p);
    if(x<=mid){
        sum+=query(p*2,x,y);
    }
    if(y>mid){
        sum+=query(p*2+1,x,y);
    }

    return sum;
}
signed main(){
    int n,m;
    cin>>n>>m;
    for(int i=1;i<=n;i++){
        cin>>w[i];
    }
    build(1,1,n);
    while(m--){
        int opt;
        cin>>opt;
        if(opt==1){
            int x,y,k;
            cin>>x>>y>>k;
            updata(1,x,y,k);
        }
        else{
            int x,y;
            cin>>x>>y;
            cout<<query(1,x,y)<<"\n";
        }
    }

    return 0;
}

样例输出11 8 16

by 1nes @ 2024-11-16 14:34:39

pushdown中tr.add先清空后下放了( )


by LeBao2023 @ 2024-11-16 14:34:58

@LLX7 pushdown改成:

void pushdown(int p){
    if(tr[p].add){
        tr[p*2].sum+=tr[p].add*(tr[p*2].r-tr[p*2].l+1);
        tr[p*2+1].sum+=tr[p].add*(tr[p*2+1].r-tr[p*2+1].l+1);
        tr[p*2].add+=tr[p].add;
        tr[p*2+1].add+=tr[p].add;
        tr[p].add=0;
    }
}

tr[p].add=0;在后面


by LLX7 @ 2024-11-16 16:01:52

@LeBao2023@1nes 已AC,谢谢


|