不是说好了线段树开4n大小吗??
查看原帖
不是说好了线段树开4n大小吗??
551417
CommonDigger楼主2024/9/1 10:51

线段树模板1题,序列长度 n≤105n\leq10^5,线段树开 4×1054\times10^5,怎么RE了?

题目链接

我的提交记录

#include "iostream"
using namespace std;
int n, m, nums[100005];
struct srgTree{
    int l, r;
    long long val, lazy;
}t[400005];
void build(int root, int l, int r){
    t[root].l=l, t[root].r=r;
    if(l==r){
        t[root].val=nums[l];
        return;
    }
    int mid=(l+r)/2;
    build(root*2, l, mid);
    build(root*2+1, mid+1, r);
    t[root].val=t[root*2].val+t[root*2+1].val;
}
void push_down(int r){
    if(!t[r].lazy) return;
    t[r*2].lazy+=t[r].lazy;
    t[r*2+1].lazy+=t[r].lazy;
    t[r*2].val+=t[r].lazy*(t[r*2].r-t[r*2].l+1);
    t[r*2+1].val+=t[r].lazy*(t[r*2+1].r-t[r*2+1].l+1);
    t[r].lazy=0;
}
void add(int root, int l, int r, int k){
    if(l<=t[root].l && t[root].r<=r){
        t[root].lazy+=k;
        t[root].val+=k*(t[root].r-t[root].l+1);
        return;
    }
    push_down(root);
    int mid=(t[root].l+t[root].r)/2;
    if(l<=mid)add(root*2, l, r, k);
    if(mid<r)add(root*2+1, l, r, k);
    t[root].val=t[root*2].val+t[root*2+1].val;
}
int sum(int root, int l, int r){
    push_down(root);
    if(l<=t[root].l && t[root].r<=r){
        return t[root].val;
    }
    long long ans=0;
    int mid=(t[root].l+t[root].r)/2;
    if(l<=mid) ans+=sum(root*2, l, r);
    if(mid<r) ans+=sum(root*2+1, l, r);
    return ans;
}
int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin >> n >> m;
    for(int i=1;i<=n;i++){
        cin >> nums[i];
    }build(1, 1, n);
    int op, l, r, k;
    for(int i=1;i<=m;i++){
        cin >> op >> l >> r;
        if(op==1){
            cin >> k;
            add(1, l, r, k);
        }else{
            cout << sum(1, l, r) << "\n";
        }
    }
}
2024/9/1 10:51
加载中...