萌新妹子线段树0pts求调

P3372 【模板】线段树 1

Lovely_Cheese @ 2024-02-04 21:04:05

RE on #1-10

#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,q,a[114514];
struct node{
    int l,r,val;
}tree[114514*4];
int lazy[114514*4];
void build(int p,int l,int r){
    tree[p].l=l; tree[p].r=r;
    tree[p].val=a[l]; lazy[p]=0;
    if(l==r) return ;
    int mid=(l+r)>>1;
    build(p<<1,l,mid);
    build(p<<1+1,mid+1,r);
    tree[p].val=tree[p<<1].val+tree[p<<1+1].val;
    return ;
}
void pushdown(int p){
    if(lazy[p]){
        tree[p<<1].val+=lazy[p]*(tree[p<<1].r-tree[p].l+1);
        tree[p<<1+1].val+=lazy[p]*(tree[p<<1+1].r-tree[p<<1+1].l+1);
        lazy[p<<1]+=lazy[p]; lazy[p<<1+1]+=lazy[p]; lazy[p]=0;
    }
    return ;
}
void update(int p,int l,int r,int val){
    if(l<=tree[p].l&&tree[p].r<=r){
        tree[p].val+=(tree[p].r-tree[p].l+1)*val;
        lazy[p]+=val;
        return ;
    }
    pushdown(p);
    int mid=(tree[p].l+tree[p].r)>>1;
    if(l<=mid) update(p<<1,l,r,val);
    if(r>mid) update(p<<1+1,l,r,val);
    tree[p].val=tree[p<<1].val+tree[p<<1+1].val;
    return ; 
}
int query(int p,int l,int r){
    if(l<=tree[p].l&&tree[p].r<=r) return tree[p].val;
    pushdown(p);
    int sum=0,mid=(tree[p].l+tree[p].r)>>1;
    if(l<=mid) sum+=query(p<<1,l,r);
    if(r>mid) sum+=query(p<<1+1,l,r);
    return sum;
}
signed main(){
    cin>>n>>q;
    for(int i=1;i<=n;i++) cin>>a[i];
    build(1,1,n);
    while(q--){
        int op;
        cin>>op;
        if(op==1){
            int l,r,x;
            cin>>l>>r>>x;
            update(1,l,r,x);
        }
        else if(op==2){
            int l,r;
            cin>>l>>r;
            cout<<query(1,l,r)<<endl;
        }
    }
    return 0;
}

by WilliamFranklin @ 2024-02-04 21:30:14

@Lovely_Cheese 学到了,拜谢


by WilliamFranklin @ 2024-02-04 21:30:39

@Lovely_Cheese 我之前一直写。。。


by ben090302 @ 2024-02-05 08:22:03

@WilliamFranklin 写了倒也不会错就是了,但是没必要


上一页 |