求大神帮看,除了第一个和后三个都wa,调了半天不知道哪有问题

P3372 【模板】线段树 1

dlrdlr @ 2023-03-02 22:54:50

#include<bits/stdc++.h>
using namespace std;
#define int long long
int a[100001],tree[400005],lazy[400005];

void build(int k,int l,int r)
{
    if(l==r){
        tree[k]=a[l];
        return;
    }
    int m=l+r>>1;
    build(2*k,l,m);
    build(2*k+1,m+1,r);
    tree[k]=tree[2*k]+tree[2*k+1];
}

void pushdown(int k,int l,int r,int c)
{
    int m=l+r>>1;
    tree[2*k]+=c*(m-l+1);lazy[2*k]+=c;
    tree[2*k+1]+=c*(r-m);lazy[2*k+1]+=c;
    lazy[k]=0;
}

void update(int k,int l,int r,int s,int t,int c)
{
    if(s<=l&&r<=t){
        tree[k]+=(r-l+1)*c;
        lazy[k]+=c;
        return;
    }
    pushdown(k,l,r,lazy[k]);
    int m=l+r>>1;
    if(s<=m)
        update(2*k,l,m,s,t,c);
    if(t>=m+1)
        update(2*k+1,m+1,r,s,t,c);
    tree[k]=tree[2*k]+tree[2*k+1];
}

int getsum(int k,int l,int r,int s,int t)
{
    if(s<=l&&r<=t){
        return tree[k];
    }
    pushdown(k,l,r,lazy[k]);
    int m=l+r>>1;
    int res=0;
    if(s<=m)
        res+=getsum(2*k,l,m,s,t);
    if(t>=m+1)
        res+=getsum(2*k+1,m+1,r,s,t);
    return res;
}

void show()
{
    for(int i=1;i<=20;i++)
        cout<<"i:"<<i<<" "<<tree[i]<<endl;
    return;
}
signed main()
{
    int n,m;
    cin>>n>>m;
    for(int i=1;i<=n;i++)
        cin>>a[i];
    build(1,1,n);

    for(int i=0;i<n;i++){
        int op,x,y,k;
        cin>>op>>x>>y;
        if(op==1){
            cin>>k;
            update(1,1,n,x,y,k);
        }
        else{
            cout<<getsum(1,1,n,x,y)<<endl;
        }
    }
    return 0;
}

by hhhh531889330 @ 2023-03-03 08:52:28

你这函数名很迷啊

区间修改打错了,区间和修改区间完全重合的时候才能打lazy

建议看看题解


|