线段树求调,实在看不出来了(玄关

P3372 【模板】线段树 1

glass_goldfish @ 2024-12-12 20:44:04

#include<bits/stdc++.h>
#define int long long
#define INF 0x3f3f3f
using namespace std;
int n,q,a[300001];
int w[300001],lzy[300001];
void build(int u,int l,int r){
    if(l==r)w[u]=a[u];
    else{
        int mid=(l+r)>>1;
        build(2*u,l,mid);build(2*u+1,mid+1,r);
        w[u]=w[2*u]+w[2*u+1];
    }
}
void update(int u,int nl,int nr,int l,int r,int k){
    if(nl>r||nr<l)return;
    else if(nl>=l&&nr<=r){
        lzy[u]+=k;
        w[u]+=(nl-nr+1)*k;
    }
    else{
        int mid=(nl+nr)>>1;
        lzy[u*2]+=lzy[u];
        w[u*2]+=(lzy[u]*(mid-nl+1));
        lzy[u*2+1]+=lzy[u];
        w[u*2+1]+=(lzy[u]*(nr-mid+1));
        lzy[u]=0;
        update(u*2,nl,mid,l,r,k);
        update(u*2+1,mid+1,nr,l,r,k);
        w[u]=w[u*2]+w[u*2+1];
    }
}
int query(int u,int nl,int nr,int l,int r){
    if(nl>r||nr<l)return 0;
    else if(nl>=l&&nr<=r)return w[u];
    else{
        int mid=(nl+nr)>>1;
        lzy[u*2]+=lzy[u];
        w[u*2]+=(lzy[u]*(mid-nl+1));
        lzy[u*2+1]+=lzy[u];
        w[u*2+1]+=(lzy[u]*(nr-mid+1));
        lzy[u]=0;
        int p=query(u*2,nl,mid,l,r)+query(u*2+1,mid+1,nr,l,r);
        return p;
    }
}
signed main(){
    cin>>n>>q;
    for(int i=1;i<=n;i++)
        cin>>a[i];
    build(1,1,n);
    while(q--){
        int opt,x,y,k;
        cin>>opt>>x>>y;
        if(opt==1){
            cin>>k;
            update(1,1,n,x,y,k);
        }
        else{
            cout<<query(1,1,n,x,y)<<"\n";
        } 
    }
    return 0;
} 

by Addicted_Game @ 2024-12-12 20:46:26

if(l==r)w[u]=a[u]; 改成 if(l==r)w[u]=a[l];


by Addicted_Game @ 2024-12-12 20:47:14

不过应该还有错误


by glass_goldfish @ 2024-12-12 20:47:40

@Addicted_Game 感谢(求壶关


by glass_goldfish @ 2024-12-12 20:48:14

@Addicted_Game 可惜还是 WA 0


by Addicted_Game @ 2024-12-12 20:52:08

你看看你自己的nl,nr,l,r,可能有些写混了,还有大于小于


by Down_syndrome @ 2024-12-12 20:52:23

@glass_goldfish 标记下传时右端点的长度是 nr-mid 而不是 nr-mid+1


by glass_goldfish @ 2024-12-12 20:54:14

@Down_syndrome 改了还是 WA 0


by Down_syndrome @ 2024-12-12 20:58:25

@glass_goldfish 逆天你 update 写的 nl-nr+1


by Down_syndrome @ 2024-12-12 21:00:12

@glass_goldfish 改了就过了。


by glass_goldfish @ 2024-12-12 21:00:31

@Down_syndrome AC 了,感谢!(求壶关


|