0pts求调

P3372 【模板】线段树 1

wise_barbarian @ 2024-08-28 21:44:34

#include<bits/stdc++.h>
#define ll long long 
using namespace std;

ll a[100010];
ll lazy[400040],sum[400040];
int n,m;

void build(int p,int front,int end){
    lazy[p]=0;
    if(front==end){
        sum[p]=a[front];
        return ;
    }
    int mid=(front+end)/2;
    build(2*p,front,mid);
    build(2*p+1,mid+1,end);
    sum[p]=sum[2*p]+sum[2*p+1];
}

void lazy_down(int p,int front,int end){
    if(lazy[p]==0) return ;
    int mid=(front+end)/2;
    lazy[2*p]+=lazy[p],lazy[2*p+1]+=lazy[p],sum[2*p]+=(mid-front+1)*lazy[p],sum[2*p+1]+=(end-mid)*lazy[p],lazy[p]=0;
}

void check(int p,int front,int end,int x,int y,int v){
    if(front>y||end<x) return ;
    if(front>=x&&end<=y) {
            lazy[p]+=v,sum[p]+=v*(front-end+1);
            return ;
        }
    lazy_down(p,front,end);
    int mid=(front+end)/2;
    if(mid>=x) check(2*p,front,mid,x,y,v);
    if(mid<y) check(2*p+1,mid+1,end,x,y,v);
    sum[p]=sum[2*p]+sum[2*p+1];
}

ll find(int p,int front,int end,int x,int y){
    if(x>end||y<front) return 0;
    if(x<=front&&y>=end) return sum[p];
    lazy_down(p,front,end);
    int mid=(front+end)>>1;
    return find(2*p,front,mid,x,y)+find(2*p+1,mid+1,end,x,y);
}

int main(){ 
    int c,x,y,z;
    cin>>n>>m;
    for(int i=1;i<=n;i++) cin>>a[i];
    build(1,1,n);
    for(int i=1;i<=m;i++){
        cin>>c;
        if(c==1){
            cin>>x>>y>>z;
            check(1,1,n,x,y,z);
        }
        else {
            cin>>x>>y;
            cout<<find(1,1,n,x,y)<<endl;
        }
    }
    return 0;
}

by wise_barbarian @ 2024-08-28 21:45:38

样例是对的,但是全WA


by Qcfff @ 2024-08-28 21:59:23

void check(int p,int front,int end,int x,int y,int v){
    if(front>y||end<x) return ;
    if(front>=x&&end<=y) {
            lazy[p]+=v,sum[p]+=v*(front-end+1);//front和end写反
            return ;
        }
    lazy_down(p,front,end);
    int mid=(front+end)/2;
    if(mid>=x) check(2*p,front,mid,x,y,v);
    if(mid<y) check(2*p+1,mid+1,end,x,y,v);
    sum[p]=sum[2*p]+sum[2*p+1];
}

by Qcfff @ 2024-08-28 21:59:37

@wyz_h


by wise_barbarian @ 2024-08-28 22:02:12

@Qcfff 谢谢大佬,已经AC


|