树状数组#8~10TLE玄关求条

P3372 【模板】线段树 1

ni_ju_ge @ 2024-09-03 19:43:31

#include<iostream>
using namespace std;
int a[1000001],n,l,r,x,k,s1,s2;
void tree_sum(int left,int right,int pos)
{
    if(left==right)
    {
        if(left>=l&&right<=r)
        {
            s2+=a[pos];
        }
        return;
    }
    int mid=(left+right)/2;
    tree_sum(left,mid,pos*2+1);
    tree_sum(mid+1,right,pos*2+2);
}
void tree_plus(int left,int right,int num,int pos)
{
    a[pos]+=s1;
    if(left==right)return;
    int mid=(left+right)/2;
    if(num<=mid)tree_plus(left,mid,num,pos*2+1);
    if(num>mid)tree_plus(mid+1,right,num,pos*2+2);
}
int main()
{
    cin>>k>>n;
    for(int j=0;j<=50000;j++)a[j]=0;
    for(int i=1;i<=k;i++)
    {
        cin>>s1;
        tree_plus(1,k,i,0);
    }
    for(int i=1;i<=n;i++)
    {
        cin>>x>>l>>r;
        if(x==1)
        {
            cin>>s1;
            for(int j=l;j<=r;j++)tree_plus(1,k,j,0);
        }
        if(x==2)
        {
            s2=0;
            tree_sum(1,k,0);
            cout<<s2<<endl;
        }
    }
}

帮帮蒟蒻,Orz


by jrzhr @ 2024-09-03 19:51:21

@ni_ju_ge 你确定这个是树状数组?


by ni_ju_ge @ 2024-09-03 19:53:03

@jrzhr 不太确定,第一次学 QAQ


by jrzhr @ 2024-09-03 19:53:32

@ni_ju_ge 建议重学


by jrzhr @ 2024-09-03 19:54:02

@ni_ju_ge 你树状数组打的跟线段树似得


by ni_ju_ge @ 2024-09-03 19:56:39

@jrzhr 原来线段树和树状数组不是一个东西呀,我打的就是线段树……(嘤嘤嘤)


by jrzhr @ 2024-09-03 19:58:07

@ni_ju_ge 你懒标记呢


by ni_ju_ge @ 2024-09-03 20:00:34

@jrzhr 感谢 dalao,先去调了(已关)


by AllenJYL @ 2024-09-03 20:00:55

线段树的区间修改不是你这样写的。


by ni_ju_ge @ 2024-09-03 21:16:01

已过,此帖结(虽然但是重写了一遍)\ 感谢各位 dalao


|