线段树后三个点TLE

P3372 【模板】线段树 1

hyh0926 @ 2024-10-06 21:43:41

rt

#include<bits/stdc++.h>
using namespace std;
int n,m,a[200000],id,x,y,k;
struct node
{
    int l,r,ne;
    int lid,rid;
}te[200000];
int init(int il,int ir)
{
    int lr=++id;
    //cout<<"lr:"<<lr<<" il:"<<il<<" ir:"<<ir<<"\n";
    te[id].l=il;
    te[id].r=ir;
    if(te[id].l==te[id].r)
    {
        te[id].ne=a[il];
        return lr;
    }
    te[lr].lid=init(il,(il+ir)/2);
    te[lr].rid=init((il+ir)/2+1,ir);
    te[lr].ne=te[te[lr].lid].ne+te[te[lr].rid].ne;
    return lr;
}
void addi(int di,int il,int ir)
{
    if(il>y||ir<x)
    {
        return;
    }
    if(il==ir)
    {
        te[di].ne+=k;
        return;
    }
    addi(te[di].lid,il,(il+ir)/2);
    addi(te[di].rid,(il+ir)/2+1,ir);
    te[di].ne=te[te[di].lid].ne+te[te[di].rid].ne;
    return;
}
int find(int di,int il,int ir)
{
    //cout<<"di:"<<di<<" il:"<<il<<" ir:"<<ir<<"\n";
    if(il>y||ir<x)
    {
        return 0;
    }
    if(il==ir)
    {
        return te[di].ne;
    }
    int ans=0;
    ans+=find(te[di].lid,il,(il+ir)/2);
    ans+=find(te[di].rid,(il+ir)/2+1,ir);
    return ans;
}
int main()
{
    cin>>n>>m;
    for(int i=1;i<=n;i++)
    {
        cin>>a[i];
    }
    init(1,n);
    for(int i=1;i<=m;i++)
    {
        int nou;
        cin>>nou;
        if(nou==1)
        {
            cin>>x>>y>>k;
            addi(1,1,n);
        }
        else
        {
            cin>>x>>y;
            cout<<find(1,1,n)<<"\n";
        }
    }
    return 0;
}

谢谢


by gavinliu266 @ 2024-10-06 21:45:36

要懒标记,否则单次修改最坏 O(n \log n) @hyh0926


by hyh0926 @ 2024-10-06 21:46:05

@zhangxisu

@forhaword

@Joker_wtf

@bulopi

我要@我能@上的所有好友来帮我


by lcfollower @ 2024-10-06 21:46:13

@hyh0926 你区间的点单点修改就成了 \mathcal O(n\log n) 时间复杂度更高了啊。

建议去学一学懒标记 lazytag


by hyh0926 @ 2024-10-06 21:48:14

@gavinliu266

@lcfollower

啥是懒标记,求链接。


by hyh0926 @ 2024-10-06 21:51:44

@gavinliu266

@lcfollower

看了眼题解,:(


by hyh0926 @ 2024-10-06 21:52:13

好难啊


by LRRabcd @ 2024-10-06 21:52:34

oi-wiki


by Rorre_y @ 2024-10-06 21:52:54

@hyh0926 模板题看题解打就可以了


|