10pts求条

P3372 【模板】线段树 1

jms23012 @ 2024-12-20 23:45:47

#include <bits/stdc++.h>
using namespace std;
long long n,a[100005],m;long long cmp,x,y,v;
struct point{
    long long l,r,tt,lazy;
}shu[500005];
inline void pushup(int num){

    shu[num].tt=shu[num<<1].tt+shu[num<<1|1].tt;
}
void zao(long long num,long long x,int y){
    shu[num].l=x;shu[num].r=y;
    if(x==y){

        shu[num].tt=a[x];
        return ;
    }
    long long mid=x+y>>1;
    zao(num<<1,x,mid);zao(num<<1|1,mid+1,y);
    pushup(num);
}
void add(long long sum){
    if(shu[sum].l>=x&&shu[sum].r<=y){
        shu[sum].lazy+=v;
        shu[sum].tt+=shu[sum].lazy*(shu[sum].r-shu[sum].l+1);
        return ;
    }
    shu[sum<<1].lazy+=shu[sum].lazy;
    shu[sum<<1|1].lazy+=shu[sum].lazy;
    shu[sum].lazy=0;
    long long mid=shu[sum].l+shu[sum].r>>1;
    if(x<=mid) add(sum<<1);
    if(y>mid) add(sum<<1|1);
    pushup(sum);
}
long long search(long long sum){
    long long res=0;
    if(shu[sum].l>=x&&shu[sum].r<=y) return shu[sum].tt;
    long long mid=shu[sum].l+shu[sum].r>>1;
    if(shu[sum].lazy!=0){
        shu[sum<<1].tt+=shu[sum].lazy*(shu[sum<<1].r-shu[sum<<1].l+1);
        shu[sum<<1|1].tt+=shu[sum].lazy*(shu[sum<<1|1].r-shu[sum<<1|1].l+1);
        shu[sum<<1].lazy+=shu[sum].lazy;
        shu[sum<<1|1].lazy+=shu[sum].lazy;
        shu[sum].lazy=0;
    }
    if(x<=mid) res+=search(sum<<1);
    if(y>mid) res+=search(sum<<1|1);
    return res;
}
int main(){
    cin>>n>>m;
    for(int i=1;i<=n;i++){
        cin>>a[i];
    }
    zao(1,1,n);
    for(int i=1;i<=m;i++){
        cin>>cmp;
        if(cmp==1){
            cin>>x>>y>>v;
            shu[1].lazy+=v;
            add(1);
        }
        else{
            cin>>x>>y;
            cout<<search(1)<<endl;
        }
    }
    return 0;
}

感觉代码内容与https://www.luogu.com.cn/discuss/1020130

完全相同,但10ptsWA


by Melo_DDD @ 2024-12-21 08:05:58

@jms23012

shu[sum].tt+=shu[sum].lazy*(shu[sum].r-shu[sum].l+1);

add 函数里这句 lazy 改成 v,不然你之后 pushdown 会重复下放


by imzfx_Square @ 2024-12-21 08:11:20

@jms23012 add 里的下传标记有问题,要改成像 search 那样的


|