差不多一模一样的代码为何过不了样例???求助!

P3372 【模板】线段树 1

zhao2008 @ 2023-07-06 21:17:45


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

int n,m,a[100005],sum[200005],tag[200005];
int opt,x,y,z;
void build(int p,int l,int r){
    if(l==r){
        sum[p]=a[l];
        return;
    }
    int mid=(l+r)/2;
    build(p*2,l,mid);
    build(p*2+1,mid+1,r);
    sum[p]=sum[p*2]+sum[p*2+1];
}
void spread(int p,int l,int r){
    tag[p*2]+=tag[p];
    tag[p*2+1]+=tag[p];
    int mid=(l+r)/2;
    sum[p*2]+=(mid-l+1)*tag[p];
    sum[p*2+1]+=(r-(mid+1)+1)*tag[p];
    tag[p]=0;
}
void change(int p,int l,int r,int a,int b,int k){
    if(a<=l&&b>=r){
        tag[p]+=k;
        sum[p]+=(r-l+1)*k;
        return;
    }
    if(tag[p]!=0)
        spread(p,l,r);
    int mid=(l+r)/2;
    if(a<=mid)
        change(p*2,l,mid,a,b,k);
    if(b>mid)
        change(p*2+1,mid+1,r,a,b,k);
    sum[p]=sum[p*2]+sum[p*2+1]; 
}
int ask(int p,int l,int r,int a,int b){
    if(a<=l&&b>=r)
        return sum[p];
    if(tag[p]!=0)
        spread(p,l,r);
    int mid=(l+r)/2,ans=0;
    if(a<=mid)
        ans+=ask(p*2,l,mid,a,b);
    if(b>mid)
        ans+=(p*2+1,mid+1,r,a,b);
    return ans;
}
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++){
        scanf("%d",&opt);
        if(opt==1){
            scanf("%d%d%d",&x,&y,&z);
            change(1,1,n,x,y,z);
        }
        else{
            scanf("%d%d",&x,&y);
            printf("%d\n",ask(1,1,n,x,y));
        }
    }
    return 0;
}

by Leonid @ 2023-07-06 21:34:53

    if(b>mid)
        ans+=(p*2+1,mid+1,r,a,b);

/yiw


by Leonid @ 2023-07-06 21:35:02

@zhao2008


by zhao2008 @ 2023-07-06 21:52:21

@Leonid 哪有问题?麻烦大佬讲一下


by Leonid @ 2023-07-07 00:31:59

@zhao2008 应改为:

    if(b>mid)
        ans+=ask(p*2+1,mid+1,r,a,b);

by zhao2008 @ 2023-07-07 08:09:09

Oh!我是**!谢谢大佬


|