线段树求调

P3372 【模板】线段树 1

_8247 @ 2022-12-04 20:11:50

#include<bits/stdc++.h>
#define ull unsigned long long
using namespace std;
ull n,m,a[100001],ans[400001],lazy[400001];
void sc()
{
    scanf("%llu%llu",&n,&m);
    for(long i=1;i<=n;i++)
        scanf("%llu",&a[i]); 
}
void build(ull p,ull l,ull r)
{
    if(l==r){ans[p]=a[l];return;}
    long mid=(l+r)>>1;
    build(p<<1,l,mid);
    build(p<<1|1,mid+1,r);
    ans[p]=ans[p<<1]+ans[p<<1|1];
}
inline void f(ull p,ull l,ull r,ull k)
{
    ans[p]+=k*(r-l+1);
    lazy[p]+=k;
    return;
}
inline void fl(ull p,ull l,ull r)
{
    long mid=(l+r)>>1;
    f(p<<1,l,mid,lazy[p]);
    f(p<<1|1,mid+1,r,lazy[p]);
    lazy[p]=0;
    return;
}
inline void change(ull al,ull ar,ull l,ull r,ull p,ull k)
{
    if(al<=l&&r<=ar)
    {
        ans[p]=k*(r-l+1);
        lazy[p]+=k;
        return;
    }
    fl(p,l,r);
    long mid=(l+r)>>1;
    if(al<=mid)
        change(al,ar,l,mid,p<<1,k);
    if(ar>mid)
        change(al,ar,mid+1,r,p<<1|1,k);
    ans[p]=ans[p<<1]+ans[p<<1|1];
    return;
}
inline long long search(ull al,ull ar,ull l,ull r,ull p)
{
    ull ret=0;
    if(al<=l&&r<=ar)
        return ans[p];
    long mid=(l+r)>>1;
    fl(p,l,r);
    if(al<=mid)
        ret+=search(al,ar,l,mid,p<<1);
    if(ar>mid)
        ret+=search(al,ar,mid+1,r,p<<1|1);
    return ret;
}
int main()
{
    ull nu,x,y,k;
    sc();
    build(1,1,n);
    while(m--)
    {
        scanf("%llu",&nu);
        switch(nu)
        {
            case 1:
                scanf("%llu%llu%llu",&x,&y,&k);
                change(x,y,1,n,1,k);
                break;
            case 2:
                scanf("%llu%llu",&x,&y);
                printf("%llu\n",search(x,y,1,n,1));
                break;
        }
    }
    return 0;
}

by Untitled10032 @ 2022-12-04 20:25:47

37行改成

ans[p]+=k*(r-l+1);

by _8247 @ 2022-12-04 20:32:06

@Untitled10032 A了,谢谢


by _8247 @ 2023-08-29 10:39:26

@killed_TLE 快改Cookie!


|