0分求助,样例正确,测试点1只有最后一个数是错的

P3372 【模板】线段树 1

Hayya @ 2024-11-13 21:49:03

#include<bits/stdc++.h>
using namespace std;
int n,m,d,x,y,k,ll,l[263000],r[263000],b[132000],lazy[263000],top;long long a[263000],ans[100100];
void work1(int i)
{
    if(x<=l[i]&&r[i]<=y) 
    {
    lazy[i]+=k;
    a[i]+=k*(r[i]-l[i]+1); 
    }
    else if((y<=r[i]&&y>=l[i])||(x<=r[i]&&x>=l[i]))
    {
        lazy[2*i]+=lazy[i]; lazy[2*i+1]+=lazy[i];
        lazy[i]=0;
        work1(2*i);work1(2*i+1);
        a[i]=a[i*2]+a[i*2+1];
    }
}
void work2(int i)
{
    if(x<=l[i]&&r[i]<=y)
    {

    ans[top]+=a[i];
    }

    else if((y<=r[i]&&y>=l[i])||(x<=r[i]&&x>=l[i])) 
    {
        lazy[2*i]+=lazy[i];lazy[2*i+1]+=lazy[i];
        if(x<=l[i*2]&&r[i*2]<=y) a[i*2]+=lazy[i]*(r[2*i]-l[2*i]+1);
        if(x<=l[i*2+1]&&r[i*2+1]<=y) a[i*2+1]+=lazy[i]*(r[2*i+1]-l[2*i+1]+1);
        lazy[i]=0;
        work2(2*i);work2(2*i+1);
        a[i]=a[i*2]+a[i*2+1];
    }
}
int main()
{
    ios::sync_with_stdio(false);
    cin>>n>>m;
    for(int i=1;i<=n;i++)
    {
        cin>>b[i];

    }
    if(n!=pow(2,log2(n))) ll=pow(2,int(log2(n))+1);
    else ll=n;
    for(int i=ll*2-1;i>=1;i--)
    {
        if(i<=ll-1) 
        {

            a[i]=a[i*2]+a[i*2+1];
            l[i]=l[2*i];r[i]=r[2*i+1]; 
        }
        else 
        {
            a[i]=b[i-ll+1];
            l[i]=i-ll+1;r[i]=i-ll+1;
        }
    }

    for(int i=1;i<=m;i++)
    {
        cin>>d;
        if(d==1)
        {
            cin>>x>>y>>k;
            work1(1);
        }
        else 
        {
            cin>>x>>y;
            top++;
            work2(1);

        }
    }
    for(int i=1;i<=top;i++)
        cout<<ans[i]<<endl;
    return 0;
}```

by lct201714 @ 2024-11-13 22:10:53

简单改了一下,代码的边界判断和懒标记下传还是有问题。

说句实话:(码风清奇)

void work1(int i){ 
    if(l[i]>y||r[i]<x) return ;
    if(x<=l[i]&&r[i]<=y) {
        lazy[i]+=k;
        a[i]+=k*(r[i]-l[i]+1); 
    }
    else{ 
        lazy[2*i]+=lazy[i]; 
        lazy[2*i+1]+=lazy[i];
        a[i*2]+=(r[i]-l[i]+1)*lazy[i];
        a[i*2+1]+=(r[i]-l[i]+1)*lazy[i];
        lazy[i]=0;
        work1(2*i);
        work1(2*i+1);
        a[i]=a[i*2]+a[i*2+1];
    }
}
void work2(int i){ 
    if(l[i]>y||r[i]<x) return ;
    if(x<=l[i]&&r[i]<=y) ans[top]+=a[i];
    else{

        lazy[2*i]+=lazy[i];
        lazy[2*i+1]+=lazy[i];
        a[i*2]+=lazy[i]*(r[2*i]-l[2*i]+1);
        a[i*2+1]+=lazy[i]*(r[2*i+1]-l[2*i+1]+1);
        lazy[i]=0;

        work2(2*i);
        work2(2*i+1);

    }
}

如果没过,勿喷


by Hayya @ 2024-11-14 00:09:22

@lct201714 重提交10分,但还是谢谢你。我也觉得我写的有逻辑问题,暂时还没想明白。 p.s.自学编程两个多月,写得确实丑陋(学了两个月写成这样还有救吗)


|