10分求调

P3372 【模板】线段树 1

yshs @ 2023-12-05 18:11:07

#include<bits/stdc++.h> 
using namespace std;
int n,m;
constexpr int N = 1e5+5;
struct Node{
    int l,r;
    long long val,tag;
}tree[N<<2];
int a[N];

void atag(int p,int d){
    tree[p].val += (tree[p].r-tree[p].l+1)*tree[p].tag;
    tree[p].tag += d;
}

void push_down(int p){
    if(tree[p].tag){
        atag(p<<1,tree[p].tag);
        atag(p<<1|1,tree[p].tag);
        tree[p].tag = 0;        
    }
}

void build(int p,int pl,int pr){
    tree[p].l = pl;
    tree[p].r = pr;
    if(pl==pr){
        tree[p].val = a[pl];
        return ;
    }
    int mid = (pl+pr)>>1;
    build(p<<1,pl,mid);
    build(p<<1|1,mid+1,pr);
    tree[p].val = tree[p<<1].val + tree[p<<1|1].val;
}

long long query(int p,int L,int R){
    if(L<=tree[p].l && tree[p].r <= R)return tree[p].val;
    push_down(p);
    int mid = (tree[p].l+tree[p].r)>>1;
    long long res = 0;
    if(L<=mid)res += query(p<<1,L,R);
    if(R>mid) res += query(p<<1|1,L,R);
    return res ;
}

void add(int p,int L,int R,int d){
    if(L<=tree[p].l && tree[p].r <= R){
        atag(p,d);
        return ;
    }
    push_down(p);
    int mid = (tree[p].l+tree[p].r)>>1;
    if (L <= mid) add(p<<1,L,R,d);
    if (R > mid) add(p<<1|1,L,R,d);
    tree[p].val = tree[p<<1].val + tree[p<<1|1].val;
}

int main(){
    ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
    cin>>n>>m;
    for(int i=1;i<=n;++i)cin>>a[i];
    build(1,1,n);
    while(m--){
        int f;
        cin>>f;
        if(f==1){
            int x,y,k;
            cin>>x>>y>>k;
            add(1,x,y,k);
        }else {
            int x,y;
            cin>>x>>y;
            cout<<query(1,x,y)<<'\n';
        }
    }
    return 0;
}

没看出和标程什么区别


by Luzhuoyuan @ 2023-12-05 18:27:28

@yshs atag() 中第一行改成 tree[p].val += (tree[p].r-tree[p].l+1)*d;


|