求助,萌新刚学OI,线段树70ptsTLE求调

P3372 【模板】线段树 1

LK_YYds @ 2024-08-09 08:57:04

rt

#include <bits/stdc++.h>
#define l long long
#define re register
#define rl re l
#define cin std::cin
#define printf std::printf
using namespace std;
l n,m,a[100006],xd[1000006];
void insert(l pos,l ll,l rr,l k,l va) 
{
    xd[pos]+=va;
    if(ll==rr) return ;
    l mi=(ll+rr)/2;
    if(k<=mi) {
        insert(pos*2+1,ll,mi,k,va);
    } else {
        insert(pos*2+2,mi+1,rr,k,va);
    }
}
void insert2(l pos,l ll,l rr,l x,l y,l k,l t) 
{
//  printf("%lld %lld %lld\n",x,y,t);
    if(x>=ll&&y<=rr)
    {
        xd[pos]+=k*t;
        if(x==2||y==3)
        {
        //  printf("%lld %lld %lld\n",x,y,t);
        }
    }
//  printf("%lld %lld %lld %lld %lld\n",pos,ll,rr,k,t); 
    if(x==y) return ;
    l mi=(x+y)/2;
    if(ll<=mi&&rr>mi)
    {
        insert2(pos*2+1,ll,rr,x,mi,k,mi-x+1); 
        insert2(pos*2+2,ll,rr,mi+1,y,k,y-mi);
    } 
    else if(ll<=mi)
    {
        insert2(pos*2+1,ll,rr,x,mi,k,mi-x+1);
    }
    else
    {
        insert2(pos*2+2,ll,rr,mi+1,y,k,y-mi);
    }
}
l find(l pos,l ll,l rr,l x,l y) {
    if(x==y) return xd[pos];
    l mi=(x+y)/2,ans=0;
    if(ll<=mi) ans+=find(pos*2+1,ll,rr,x,mi);
    if(rr>mi) ans+=find(pos*2+2,ll,rr,mi+1,y);
    return ans;
}
void mian() 
{
    cin>>n>>m;
    for(rl i=1; i<=n; i++) 
    {
        cin>>a[i];
        insert(0,1,n,i,a[i]);
    }
    for(rl i=1; i<=m; i++) 
    {
        l opt,x,y,k;
        cin>>opt;
        if(opt==1) 
        {
            cin>>x>>y>>k;
            insert2(0,x,y,1,n,k,y-x+1);
        } 
        else 
        {
            cin>>x>>y;
            printf("%lld\n",find(0,x,y,1,n));
        }
    }
}
int main() {
    mian();
    return 0;
}

by Ace_ace @ 2024-08-09 09:01:23

用树状数组做


by KAqwq @ 2024-08-09 09:03:43

重构。


by Ace_ace @ 2024-08-09 09:06:42

@KAqwq 赞


by LK_YYds @ 2024-08-09 09:07:46

只是TLE没必要重构吧


by InfiniteRobin @ 2024-08-09 09:11:07

加个快读试试?


by InfiniteRobin @ 2024-08-09 09:15:04

不对,你这个没加懒标记。


by InfiniteRobin @ 2024-08-09 09:17:27

@LK_YYds


by SW_YM @ 2024-08-12 16:08:24

lazytag是区间加的必要部分吧


|