70pts求调

P3372 【模板】线段树 1

Gordon1 @ 2024-12-21 11:53:45

#include<bits/stdc++.h>
using namespace std;
int n,m;
int a[400005];
struct Node
{
    int l,r,num,lz;
}tree[400005];
void build(int l,int r,int index)
{
    tree[index].l=l;
    tree[index].r=r;
    tree[index].lz=0;
    if(l==r)
    {
        tree[index].num=a[l];
        return ;
    }
    int mid=l+(r-l)/2;
    build(l,mid,index*2);
    build(mid+1,r,index*2+1);
    tree[index].num=tree[index*2].num+tree[index*2+1].num;
    return ;
}
void pushdown(int index)
{
    if(tree[index].lz!=0)
    {
        tree[2*index].lz+=tree[index].lz;
        tree[2*index+1].lz+=tree[index].lz;
        int mid=(tree[index].l+tree[index].r)/2;
        tree[2*index].num+=tree[index].lz*(mid-tree[2*index].l+1);
        tree[2*index+1].num+=tree[index].lz*(tree[2*index+1].r-mid);
        tree[index].lz=0;
    }
    return ;
}
void add(int index,int l,int r,int k)
{
    if(tree[index].l>=l&&tree[index].r<=r)
    {
        tree[index].num+=k*(tree[index].r-tree[index].l+1);
        tree[index].lz+=k;
        return ;
    }
    pushdown(index);
    if(tree[index*2].r>=l)
        add(2*index,l,r,k);
    if(tree[index*2+1].l<=r)
        add(2*index+1,l,r,k);
    tree[index].num=tree[2*index].num+tree[2*index+1].num;
    return ;
}
int search(int index,int l,int r)
{
    if(tree[index].l>=l&&tree[index].r<=r)
    {
        return tree[index].num;
    }
    pushdown(index);
    int num=0;
    if(tree[index*2].r>=l)
        num+=search(2*index,l,r);
    if(tree[index*2+1].l<=r)
        num+=search(2*index+1,l,r);
        return num;
}
int op,x,y,z;
int main()
{
    cin>>n>>m;
    for(int i=1;i<=n;++i)
    {
        cin>>a[i];
    }
    build(1,n,1);
    for(int i=1;i<=m;++i)
    {
        cin>>op;
        if(op==1)
        {
            cin>>x>>y>>z;
            add(1,x,y,z);
        }
        else
        {
            cin>>x>>y;
            cout<<search(1,x,y)<<endl;
        }
    }
    return 0;
}

8,9,10 WA,求调


by JoyLosingK @ 2024-12-21 12:11:53

@Gordon1

要开 long long


by Gordon1 @ 2024-12-21 21:01:47

@JoyLosingK已A,感谢大佬,已关


|