萌新刚学OI 求调悬关

P3372 【模板】线段树 1

zxr_zwgh @ 2024-07-31 09:19:19

RT

#include<bits/stdc++.h>
using namespace std;
struct node{
    int left,right;
    int value,lazy=0;
}tree[4000005];
int a[1000005];
void build(int l,int r,int root){
    tree[root].left=l,tree[root].right=r;
    if(tree[root].left==tree[root].right){
        tree[root].value=a[l];
        return;
    }
    int mid=(tree[root].left+tree[root].right)/2;
    build(l,mid,tree[root].left);
    build(mid+1,r,tree[root].right);
    tree[root].value=tree[root*2].value+tree[root*2+1].value;
}
void spread(int root){
    if(tree[root].left==tree[root].right){
        return;
    }
    int lazy=tree[root].lazy;
    tree[root*2].lazy+=lazy;
    tree[root*2+1].lazy+=lazy;
    tree[root*2].value+=lazy*(tree[root*2].right-tree[root*2].left+1);
    tree[root*2+1].value+=lazy*(tree[root*2+1].right-tree[root*2].left+1);
    tree[root].lazy=0;
}
void update(int root,int l,int r,int v){
    if(tree[root].left>=l&&tree[root].right<=r){
        tree[root].lazy=v;
        tree[root].value+=(tree[root].right-tree[root].left+1);
        return;
    }
    spread(root);
    int mid=(tree[root].left+tree[root].right)/2;
    if(l<=mid) update(root*2,l,r,v);
    if(r>mid) update(root*2+1,l,r,v);
    tree[root].value=tree[root*2].value+tree[root*2+1].value;
}
long long query(int root,int l,int r){
    long long ans=0;
    if(tree[root].left>=l&&tree[root].right<=r){
        return tree[root].value;
    }
    spread(root);
    int mid=(tree[root].left+tree[root].right)/2;
    if(l<=mid) ans+=query(root*2,l,r);
    if(r>mid) ans+=query(root*2+1,l,r);
    return ans;
}
int main(){
    ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
    int n,q;
    cin>>n>>q;
    for(int i=1;i<=n;i++){
        cin>>a[i];
    }
    build(1,n,1) ;
    while(q--){
        int op;
        cin>>op;
        if(op==1){
            int l,r,v;
            cin>>l>>r>>v;
            update(1,l,r,v);
        }else if(op==2){
            int l,r;
            cin>>l>>r;
            cout<<query(1,l,r)<<"\n";
        }
    }
    return 0;
}

by Brilliant11001 @ 2024-07-31 09:43:42


by Brilliant11001 @ 2024-07-31 09:44:31

@zxr_zwgh 没关系慢慢来,多打几遍就记住了


by zxr_zwgh @ 2024-07-31 09:49:09

@Brilliant11001 不好意思刚看见,感谢,A了


by OIer_dcy__AK_IOI @ 2024-07-31 15:15:38

@zxr_zwgh 你不是也偷偷学线段树吗


by zxr_zwgh @ 2024-07-31 22:23:58

@kdy_c_dcy eee,kdy5月就交了,但我板子默不出来qwq


上一页 |