0分线段树求调QwQ

P3372 【模板】线段树 1

shihang2024 @ 2024-10-29 13:31:54

#include<iostream>
using namespace std;
typedef long long ll;
const int MAX = 1e6+10;
#define ls(p) p<<1
#define rs(p) p<<1|1
struct Node
{
    ll l,r;
    ll sum,add;
}tree[MAX<<2];
ll n,m,a[MAX];
void push_up(ll p)
{
    tree[p].sum=tree[ls(p)].sum+tree[rs(p)].sum;
}
void build(ll p,ll l,ll r)
{
    tree[p].l=l,tree[p].r=r;
    if(l==r)
    {
        tree[p].sum=a[l];
        return;
    }
    ll mid=(l+r)>>1;
    build(ls(p),l,mid);
    build(rs(p),mid+1,r);
    push_up(p);
}
void addtag(ll p,ll tag)
{
    ll pl=tree[p].l,pr=tree[p].r;
    tree[p].add+=tag;
    tree[p].sum=tag*(pr-pl+1);
}
void push_down(ll p)
{
    //ll pl=tree[p].l,pr=tree[p].r;
    if(tree[p].add)
    {
        //ll mid=(pl+pr)>>1;
        ll tag=tree[p].add;
        addtag(ls(p),tag);
        addtag(rs(p),tag);
        tree[p].add=0;
    }
}
void add(ll p,ll l,ll r,ll d)
{
    ll pl=tree[p].l,pr=tree[p].r;
    if(l<=pl&&pr<=r)
    {
        addtag(p,d);
        return;
    }
    push_down(p);
    ll mid=(pl+pr)>>1;
    if(l<=mid) add(ls(p),l,r,d);
    if(r>mid) add(rs(p),l,r,d);
    push_up(p);
}
ll query(ll p,ll l,ll r)
{
    ll pl=tree[p].l,pr=tree[p].r;
    if(l<=pl&&pr<=r) return tree[p].sum;
    push_down(p);
    ll ans=0,mid=(pl+pr)>>1;
    if(l<=mid) ans+=query(ls(p),l,r);
    if(mid<r) ans+=query(rs(p),l,r);
    return ans;
}
int main()
{
    scanf("%lld %lld",&n,&m);
    for(int i=1;i<=n;i++) scanf("%lld",a+i);
    build(1,1,n);
    while(m--)
    {
        int op;scanf("%d",&op);
        if(op==1)
        {
            ll x,y,k;scanf("%lld %lld %lld",&x,&y,&k);
            add(1,x,y,k);
        }
        else if(op==2)
        {
            ll x,y;scanf("%lld %lld",&x,&y);
            printf("%lld\n",query(1,x,y));
        }
    }
    return 0;
}

by jzjr @ 2024-10-29 13:56:28

void addtag(ll p,ll tag)
{
    ll pl=tree[p].l,pr=tree[p].r;
    tree[p].add+=tag;
    tree[p].sum=tag*(pr-pl+1);
}

这里是 += 捏


by jzjr @ 2024-10-29 13:57:26

@shihang2024


by shihang2024 @ 2024-10-29 14:08:45

这里是添加lazy tag标记,需要考虑先前的tag


by shihang2024 @ 2024-10-29 14:10:16

即使更改'+=',仍然0分QWQ

记录


|