求助,线段树0pts

P3372 【模板】线段树 1

zhangzhixu000001 @ 2024-04-24 20:09:23

#include <bits/stdc++.h>
using namespace std;
#define io ios::sync_with_stdio(0)
const int maxn=5e5;
struct tree{
    long long l,r;
    long long sum,tag;
}tr[maxn<<2];
long long num[maxn];
inline long long ls(long long n){return n<<1;}
inline long long rs(long long n){return n<<1|1;}
inline void up(long long n)
{
    tr[n].sum=tr[ls(n)].sum+tr[rs(n)].sum;
    return;
}
inline void build(long long l,long long r,long long p)
{
    tr[p].l=l;tr[p].r=r;
    if (l==r)
    {
        tr[p].sum=num[l];
        return;
    }
    long long mid=(l+r)>>1;
    build(l,mid,ls(p));
    build(mid+1,r,rs(p));
    up(p);
}
inline void tagadd(long long d,long long l,long long r,long long p)
{
    tr[p].tag+=d;
    tr[p].sum+=d*(r-l+1);   
}
inline void pushdown(long long p,long long l,long long r)
{
    if (tr[p].tag)
    {
        int mid=(l+r)>>1;
        tagadd(tr[p].tag,l,mid,ls(p));
        tagadd(tr[p].tag,mid+1,r,rs(p));
        tr[p].tag=0;
    }
 }
inline long long query(long long l,long long r,long long p)
{
    if (l<=tr[p].l&&tr[p].r<=r) return tr[p].sum;
    pushdown(p,l,r);
    long long tot=0;
    if (tr[ls(p)].r>=l) tot+=query(l,r,ls(p));
    if (tr[rs(p)].l<=r) tot+=query(l,r,rs(p));
    return tot; 
} 
inline void updata(long long l,long long r,long long p,long long num)
{
    if (tr[p].l>=l&&tr[p].r<=r) 
    {
        tagadd(num,tr[p].l,tr[p].r,p);
        return;
    }
    pushdown(p,tr[p].l,tr[p].r);
    if(tr[ls(p)].r>=l) updata(l,r,ls(p),num);
    if(tr[rs(p)].l<=r) updata(l,r,rs(p),num);
    up(p);
}

int main() {
    io;
    long long n,m,a,b,c,d;cin>>n>>m;
    for (long long i=1;i<=n;i++) cin>>num[i];
    build(1,n,1);
    for (long long i=1;i<=m;i++)
    {
        cin>>a>>b>>c;
        if (a==1) cin>>d;
        switch(a)
        {
            case 1:updata(b,c,1,d);break;
            case 2:cout<<query(b,c,1)<<endl;break;
            default:break;
         } 
    }
    return 0;
}

|