求助!!!样例都过不了

P3372 【模板】线段树 1

yjy_echo @ 2024-04-18 16:36:10

#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int N=1e5+5;
int n,m,a,x,y,k,ans[N];
struct edge{
    int l,r;
    ll sum;
    ll lz;
}e[N<<2];

inline ll ls(ll x){
    return x<<1;
}

inline ll rs(ll x){
    return x<<1|1;
}

void build(int k,int l,int r){
    e[k].l=l;
    e[k].r=r;
    if(l==r){
        e[l].sum=ans[l];
        return;
    }
    int mid=(l+r)/2;
    build(ls(k),l,mid);
    build(rs(k),mid+1,r);
    e[k].sum=e[k*2].sum+e[k*2+1].sum;
}

void pushdown(int u){
    e[u*2].lz+=e[u].lz;
    e[u*2+1].lz+=e[u].lz;
    e[u*2].sum=e[u].lz*(e[u*2].r-e[u*2].l+1);
    e[u*2+1].sum=e[u].lz*(e[u*2+1].r-e[u*2+1].l+1);
    e[u].lz=0;
}

void pushup(int u){
    e[u].sum=e[u*2].sum+e[u*2+1].sum;
} 

void update(int l,int r,int u,int x)
{
    if(e[u].r==0||e[u].l==0) return;
    if(l<=e[u].l&&e[u].r<=r){
        e[u].lz+=x;
        e[u].sum+=x*(e[u].r-e[u].l+1);
        return;
    }
    int mid=(e[u].r+e[u].l)>>1;
    pushdown(u);
    if(l<=mid) update(l,r,u*2,x);
    if(r>mid) update(l,r,u*2+1,x);
    pushup(u);
}

int query(int u,int l,int r,int nl,int nr){
    ll res=0;
    if(e[u].l>r||e[u].r<l) return 0;
    if(e[u].l>=l&&e[u].r<=r) return e[u].sum;
    int mid=(nl+nr)>>1;
    pushdown(u);
    if(l<=mid) res+=query(ls(u),l,r,nl,mid);
    if(y>mid) res+=query(rs(u),l,r,mid+1,nr);
}

int main(){
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++) scanf("%d",&ans[i]);
    build(1,1,n);
    for(int i=1;i<=m;i++){
        scanf("%d",&a);
        if(a==1){
            scanf("%d%d%d",&x,&y,&k);
            update(x,y,1,k);
        } 
        else{
            scanf("%d%d",&x,&y);
            printf("%lld\n",query(1,x,y,1,n));
        }
    }
    return 0;
}

by xuhaotian @ 2024-04-18 16:41:42

@yangjingyao2011 query 没有返回值


by xuhaotian @ 2024-04-18 16:44:33

pushdown的sum更新时改为+


by yjy_echo @ 2024-04-18 16:47:43

@xuhaotian 输出3,5,11,还是不对


by xuhaotian @ 2024-04-18 16:48:43

你的build中e[l].sum=ans[l];应该为 e[k].sum=ans[l];


by xuhaotian @ 2024-04-18 16:49:00

@yangjingyao2011 这下就对了


by xuhaotian @ 2024-04-18 16:51:08

还要开long long


by xuhaotian @ 2024-04-18 16:52:48

你query返回值是int


by yjy_echo @ 2024-04-18 16:53:00

@xuhaotian 感谢,已过


by yjy_echo @ 2024-04-18 16:53:36

@yangjingyao2011 此帖结


|