求助QWQ

P3372 【模板】线段树 1

Benjieming123 @ 2023-04-04 21:29:40

70分,最后三个RE了

#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 5 ;
int n, m ;
int a[maxn] ;
int num, sum[maxn], lc[maxn], rc[maxn] ;

void Pushup(int p){
    sum[p] = sum[lc[p]] + sum[rc[p]] ;
}

void Build(int l, int r, int &p){
    if(!p) p = ++num ;
    if(l == r){
        sum[p] = a[l] ;
        return ;
    }
    int mid = (l + r) / 2 ;
    Build(l, mid, lc[p]) ;
    Build(mid + 1, r, rc[p]) ;
    Pushup(p) ;
}

void update(int l, int r,int p, int L, int R, int k){
    if(l == r){
        sum[p] += k ;
        return ;
    }
    int mid = (l + r) / 2 ;
    if(L <= mid)update(l, mid, lc[p], L, R, k) ;
    if(R >= mid + 1)update(mid + 1, r, rc[p], L, R, k) ;
    sum[p] = sum[lc[p]] + sum[rc[p]] ;
}

long long query(int l, int r, int p, int L, int R){
    if(L <= l && r <= R){
        return sum[p] ;
    }
    int mid = (l + r) / 2 ;
    long long tot = 0 ;
    if(L <= mid) tot += query(l, mid, lc[p], L, R) ;
    if(R >= mid + 1) tot += query(mid + 1, r, rc[p], L, R) ;
    return tot ;
}

int root ;
void Read(){
    scanf("%d %d", &n, &m ) ;
    for(int i = 1; i <= n; i++){
        scanf("%d", &a[i] ) ;
    }
    Build(1, n, root) ;
    for(int i = 1; i <= m; i++){
        int flag = 0 ;
        scanf("%d", &flag ) ;
        if(flag == 1){
            int x, y, k ;
            scanf("%d %d %d", &x, &y, &k ) ;
            update(1, n, 1, x, y, k) ;
        }else{
            int x, y ;
            scanf("%d %d", &x, &y ) ;
            long long ans = query(1, n, 1, x, y) ;
            printf("%lld\n", ans ) ;
        }
    }
}

int main(){
    Read() ;
}

by HuangTian @ 2023-04-04 21:43:53

线段树要开4n空间


by HuangTian @ 2023-04-04 21:45:59

开O2,快读


by Benjieming123 @ 2023-04-05 21:05:38

@HuangTian 4倍开了,o2开了,快读用了,最后三个tle了


by HuangTian @ 2023-04-08 08:25:54

线段树写假了


by Benjieming123 @ 2023-04-10 21:46:07

@HuangTian 已经改AC了,谢谢大佬


|