复赛在即,重写板子,写炸了,马蜂优良,求调

P3372 【模板】线段树 1

巫晴枫123456 @ 2024-10-21 22:36:18

#include<bits/stdc++.h>
using namespace std;
#define int long long
int n,m,b,c,d,e,a[100001],tree[400001],lazy[400001];
void build(int id,int l,int r){
    if(l == r){
        tree[id] = a[l];
        return ;
    }   
    int mid = l + ((r-l)>>1);
    build(id<<1,l,mid);
    build((id<<1)|1,mid+1,r);
    tree[id] = tree[id<<1] + tree[(id<<1)|1];
    return ;
}
void down(int id,int l,int r,int mid){
    tree[id<<1] += lazy[id] * (mid-l+1);
    tree[(id<<1)|1] += lazy[id] * (r-mid);
    lazy[id<<1] += lazy[id];
    lazy[(id<<1)|1] += lazy[id];
    lazy[id] = 0; 
    return ;
}
void update(int id,int w,int l,int r,int o,int p){
    if(l <= o&&p <= r){
        tree[id] += w * (r-l+1);
        lazy[id] += w;
        return ;
    }
    int mid = o + ((p-o)>>1);
    if(lazy[id])    down(id,o,p,mid);
    if(l <= mid)    update((id<<1),w,l,r,o,mid);
    if(mid < r)     update((id<<1)|1,w,l,r,mid+1,p);
    tree[id] = tree[id<<1] + tree[(id<<1)|1];
    return ;
}
int out(int id,int l,int r,int o,int p){
    if(l <= o&&p <= r){
        return tree[id];
    }
    int mid = o + ((p-o)>>1);
    if(lazy[mid])   down(id,o,p,mid);
    int ans1=0,ans2=0;
    if(l <= mid)    ans1 = out((id<<1),l,r,o,mid);
    if(mid < r)     ans2 = out((id<<1)|1,l,r,mid+1,p); 

    return ans1+ans2;
}
signed main(){
    cin >> n >> m;
    for(int i = 1; i <= n; i++){
        cin >> a[i];
    }
    build(1,1,n);
    while(m--){
        cin >> b >> c >> d;
        if(b == 2){
            cout << out(1,c,d,1,n) <<endl;
        }else{
            cin >> e;
            update(1,e,c,d,1,n);
        }
    }
    return 0;
}

by 巫晴枫123456 @ 2024-10-22 13:52:59

已关两位dalao,我个入机, 此帖结


上一页 |