help!

P3372 【模板】线段树 1

CSP_JAKME @ 2024-10-19 14:35:07

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+10;
int n,m,a[maxn],tree[maxn*4];
int lzy[maxn*4]; 
void pushup(int u){
    tree[u]=tree[u*2]+tree[u*2+1];
}
void build(int u,int left,int right){
    if(left==right){
        tree[u]=a[left];
        return;
    }
    int mid=(left+right)/2;
    build(u*2,left,mid);
    build(u*2+1,mid+1,right);
    pushup(u);
    return;
}
bool intheline(int L,int R,int l,int r){
    return l<=L&&r>=R;
}
bool cdline(int L,int R,int l,int r){
    return L<=r&&R>=l;
}
int sum(int u,int left,int right,int l,int r){
    if(intheline(left,right,l,r)) return tree[u];
    else if(cdline(left,right,l,r)){
        int mid=(left+right)/2;
        return sum(u*2,left,mid,l,r)+sum(u*2+1,mid+1,right,l,r);
    }
    return 0;
}
void make(int u,int k,int len){
    lzy[u]+=k;
    tree[u]+=len*k;
    return;
}
void pushdown(int u,int left,int right){
    int mid=(left+right)/2;
    make(u*2,lzy[u],mid-left+1);
    make(u*2+1,lzy[u],right-mid);
    lzy[u]=0;
    return;
}
/*
void printt(int u){
    if(u>2*n-1) return;
    cout << tree[u] << " ";
    printt(u*2);
    printt(u*2+1);
}
*/
void update(int u,int left,int right,int l,int r,int k){
    if(intheline(left,right,l,r)){
        make(u,k,right-left+1);
        return;
    }else if(cdline(left,right,l,r)){
        int mid=(left+right)/2;
        pushdown(u,left,right);
        update(u*2,left,mid,l,r,k);
        update(u*2+1,mid+1,right,l,r,k);
        pushup(u);
    }else return;
}
int main(){
    cin >> n >> m;
    for(int i=1;i<=n;i++) scanf("%d",&a[i]);
    build(1,1,n);
    for(int i=1;i<=m;i++){
        int opt,x,y;
        cin >> opt >> x >> y;
        if(opt==1){
            int k;
            cin >> k;
            update(1,1,n,x,y,k);
        }else{
            printf("%d\n",sum(1,1,n,x,y));
        }
    }
    return 0;
}

by qzmoot @ 2024-10-19 14:54:53

@CSP_JAKME 输出中间值调试


|