刚学线段树,70分tle求调

P3372 【模板】线段树 1

only_joker @ 2023-12-28 18:07:01

#include<bits/stdc++.h>
using namespace std;
long long ma[400025],a[100005],n,m,z,x,y,kk,sum; 
void build(long long k,long long l,long long r){
    if(l==r)
    {
        ma[k]=a[l];
        return;
    }
    long long mid=(l+r)/2;
    build(k*2,l,mid);
    build(k*2+1,mid+1,r);
    ma[k]=ma[k*2]+ma[k*2+1];
}
void query(long long k,long long l,long long r,long long x,long long y){
    if(l>y||r<x) return;
    if(l>=x&&r<=y)
    {
        sum+=ma[k];
        return; 
    }
    if(r>y||l<x)
    {
        long long mid=(l+r)/2;
        query(k*2,l,mid,x,y);
        query(k*2+1,mid+1,r,x,y);
    }
}
void query1(long long k,long long l,long long r,long long x,long long y){
    if(l>y||r<x) return;
    if(l==r)
    {
        ma[k]+=kk;
        return; 
    }
    long long mid=(l+r)/2;
    query1(k*2,l,mid,x,y);
    query1(k*2+1,mid+1,r,x,y);
    ma[k]=ma[k*2]+ma[k*2+1];
}
int main(){
    cin>>n>>m;
    for(long long i=1;i<=n;i++)
    {
        cin>>a[i];
    }
    build(1,1,n);
    for(long long i=1;i<=m;i++)
    {
        sum=0;
        cin>>z;
        if(z==1)
        {
            cin>>x>>y>>kk;
            query1(1,1,n,x,y);
        }
        else
        {
            cin>>x>>y;
            query(1,1,n,x,y);
            cout<<sum<<endl;
        }
    }
}

悬赏一关,在线


by Qcfff @ 2023-12-28 18:11:03

懒标记


by Linge_Zzzz @ 2023-12-28 18:12:29

没看懂,建议先把线段树搞明白


by only_joker @ 2023-12-28 18:12:49

@Qcfff 谢谢,此贴结


|