RE求调

P3372 【模板】线段树 1

wuwenqi11111 @ 2024-11-24 11:38:22

#include<bits/stdc++.h>
using namespace std;
const int N=1e6+5;
int number[N],n,m,op,x,y,k;
inline int read(){
    int k=0,f=1;
    char ch=getchar();
    while(ch<'0'||ch>'9'){
        if(ch=='-') f=-1;
        ch=getchar();
    }
    while(ch>='0'&&ch<='9'){
        k=k*10+ch-'0';
        ch=getchar();
    }
    return k*f;
}
struct Node{
    int l,r,sum,lazy;
    Node(){l=r=sum=lazy=0;}
}a[N*4];
void update(int k){
    a[k].sum=a[k<<1].sum+a[k<<1|1].sum+a[k].lazy;
}
void build(int k,int l,int r){
    a[k].l=l,a[k].r=r;
    if(l==r){
        a[k].sum=number[l];
        return;
    }
    int mid=l+r>>1;
    build(2*k,l,mid);
    build(2*k+1,mid+1,r);
    update(k);
}//建树
void changeSegment(int k,int l,int r,int x){
    if(a[k].l==l&&a[k].r==r){
        a[k].sum+=(r-l+1)*x;
        a[k].lazy+=x;
        return;
    }
    int mid=l+r>>1;
    if(r<=mid) changeSegment(2*k,l,r,x);
    else if(l>mid) changeSegment(2*k+1,l,r,x);
    else changeSegment(2*k,l,mid,x),changeSegment(2*k+1,mid+1,r,x);
    update(k);
}//区间修改
void push_down(int k){
    if(a[k].l==a[k].r){
        a[k].lazy=0;
        return;
    }
    a[k*2].sum+=(a[k*2].r-a[k*2].l+1)*a[k].lazy;
    a[k*2+1].sum+=(a[k*2+1].r-a[k*2+1].l+1)*a[k].lazy;
    a[k*2].lazy+=a[k].lazy;
    a[k*2+1].lazy+=a[k].lazy;
    a[k].lazy=0;
}//下传标记
int query(int k,int l,int r){
    if(a[k].lazy) push_down(k);
    if(a[k].l==l&&a[k].r==r) return a[k].sum;
    int mid=l+r>>1;
    if(r<=mid) return query(k*2,l,r);
    if(l>mid) return query(k*2+1,l,r);
    return query(k*2,l,mid)+query(k*2+1,mid+1,r);
}//区间查询
int main(){
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;++i) number[i]=read();
    build(1,1,n);
    while(m--){
        scanf("%d",&op);
        if(op==1){
            scanf("%d%d%d",&x,&y,&k);
            changeSegment(1,x,y,k);
        }
        else{
            scanf("%d%d",&x,&y);
            printf("%d\n",query(1,x,y));
        }
    }
    return 0;
}

by lingquan @ 2024-11-24 13:40:08

似乎并不需要高精度(


by lingquan @ 2024-11-24 13:47:54

以及你写的有点麻烦,要不改下(


|