线段树模板

在这里插入图片描述

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<set>
#include<string.h>
#include<vector>
#include<set>
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define ll long long
#define inf 0x3f3f3f3f
const int maxn=1e5+5;
using namespace std;
ll n,m,mark[4*maxn],tree[4*maxn],A[maxn];
inline ll read()
{
    ll ans=0;
    char c=getchar();
    while(!isdigit(c))
    {
        c=getchar();
    }
    while(isdigit(c))
    {
        ans=ans*10+c-'0';
        c=getchar();
    }
    return ans;

}
void build (ll l=1,ll r=n,ll p=1)
{
    if(l==r)tree[p]=A[l];
    else
    {
        ll mid=(l+r)/2;
        build(l,mid,2*p);
        build(mid+1,r,2*p+1);
        tree[p]=tree[2*p]+tree[2*p+1];
    }
}
void push_down(ll p,ll len)
{
    mark[2*p]+=mark[p];
    mark[2*p+1]+=mark[p];
    tree[2*p]+=mark[p]*(len-len/2);
    tree[2*p+1]+=mark[p]*(len/2);
    mark[p]=0;
}
void update(ll l,ll r,ll d,ll p=1,ll cl=1,ll cr=n)
{
    if(cl>r||cr<l)
        return;
    else if(cl>=l&&cr<=r)
    {

        tree[p]+=d*(cr-cl+1);
        if(cr>cl)mark[p]+=d;
    }
    else
    {
        ll mid=(cl+cr)/2;
        push_down(p,cr-cl+1);
        update(l,r,d,2*p,cl,mid);
        update(l,r,d,2*p+1,mid+1,cr);
        tree[p]=tree[2*p]+tree[2*p+1];
    }
}
ll  query(ll l,ll r,ll p=1,ll cl=1,ll cr=n)
{
    if(cl>r||cr<l)
        return 0;
    else if(cl>=l&&cr<=r)
    {
         return tree[p];
    }
    else
    {
        ll mid=(cl+cr)/2;
        push_down(p,cr-cl+1);
        return query(l,r,2*p,cl,mid)+query(l,r,2*p+1,mid+1,cr);
    }
}
int main()
{
    n=read();
    m=read();
    for(int i=1;i<=n;i++)
    {
        A[i]=read();
    }
    build();
    for(int i=0;i<m;i++)
    {
        ll oper=read(),l=read(),r=read();
        if(oper==1)
        {
            ll d=read();
            update(l,r,d);
        }
        else
        {
            printf("%lld\n",query(l,r));
        }
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值