70分求助!

P3372 【模板】线段树 1

Xuwindows_WS @ 2024-07-09 13:40:27

70分求助!
问题知道了,无法处理负权。但是不知道怎么改啊...

#include<bits/stdc++.h>
using namespace std;
int a[1000010];
int tr[4000040];
int lz[4000040];
void build(int l,int r,int id)
{
    if(l==r)
    {
        tr[id]=a[l];
        return;
    }
    int mid=(l+r)/2;
    build(l,mid,id*2);
    build(mid+1,r,id*2+1);
    tr[id]=tr[id*2]+tr[id*2+1];
}
void upd(int lu,int ru,int ln,int rn,int id,int k)
{
    if(lu<=ln&&ru>=rn)
    {
        tr[id]+=(rn-ln+1)*k;
        lz[id]+=k;
        return;
    }
    int mid=(ln+rn)/2;
    if(lz[id]!=0&&ln!=rn)
    {
        tr[id*2]+=lz[id]*(mid-ln+1);
        tr[id*2+1]+=lz[id]*(rn-mid);
        lz[id*2]+=lz[id];
        lz[id*2+1]+=lz[id];
        lz[id]=0;
    }
    if(lu<=mid)upd(lu,ru,ln,mid,id*2,k);
    if(ru>mid)upd(lu,ru,mid+1,rn,id*2+1,k);
    tr[id]=tr[id*2]+tr[id*2+1];
}
int getsum(int lc,int rc,int ln,int rn,int id)
{
    if(lc<=ln&&rc>=rn)
    {
        return tr[id];
    }
    int mid=(ln+rn)/2;
    if(lz[id]!=0)
    {
        tr[id*2]+=lz[id]*(mid-ln+1);
        tr[id*2+1]+=lz[id]*(rn-mid);
        lz[id*2]+=lz[id];
        lz[id*2+1]+=lz[id];
        lz[id]=0;
    }
    int sum=0;
    if(lc<=mid)sum+=getsum(lc,rc,ln,mid,id*2);
    if(rc>mid)sum+=getsum(lc,rc,mid+1,rn,id*2+1);
    return sum;
}
int main()
{
    int n,m;
    cin>>n>>m;
    for(int i=1;i<=n;i++)
    {
        cin>>a[i];
    }
    build(1,n,1);
    for(int i=1;i<=m;i++)
    {
        int op;
        cin>>op;
        if(op==1)
        {
            int x,y,k;
            cin>>x>>y>>k;
            upd(x,y,1,n,1,k);
        }
        else if(op==2)
        {
            int x,y;
            cin>>x>>y;
            cout<<getsum(x,y,1,n,1)<<endl;
        }
    }
    return 0;
}

by ybc2027zhanglingrui @ 2024-07-09 13:43:01

@Xu_Window 进度问题,二分的(l+r)/2改为l+(r-l)>>1


by ybc2027zhanglingrui @ 2024-07-09 13:43:44

@Xu_Window 十年OI一场空,___


by Xuwindows_WS @ 2024-07-09 15:56:24

谢谢


|