线段树速撸

点我飞去垃圾模板题

第一次尝试速撸线段树,只撸了个区间修改 区间查询的比较菜的线段树

用时17:33.5

第一遍测样例错了,仔细看了看发现change字数后没有pushup

#include<iostream>
#include<cstdio>
#include<cstring>
#define LL long long
#define pushup(rt) tree[rt]=tree[rt<<1]+tree[rt<<1|1]
using namespace std;

inline void inl(LL &p,char c=getchar(),bool f=0)
{
    while((c<'0' or c>'9') and c!='-')
        c=getchar();
    p=0;
    if(c=='-')
        f=1,c=getchar();
    while(c>='0' and c<='9')
        p=p*10+c-'0',c=getchar();
    if(f)
        p=-p;
}
inline void in(int &p,char c=getchar(),bool f=0)
{
    while((c<'0' or c>'9') and c!='-')
        c=getchar();
    p=0;
    if(c=='-')
        f=1,c=getchar();
    while(c>='0' and c<='9')
        p=p*10+c-'0',c=getchar();
    if(f)
        p=-p;
}

int n,m;
LL tree[100001<<2],add[100001<<2],a[100001];

inline void build(int rt,int l,int r)
{
    if(l==r)
    {
        tree[rt]=a[l];
        return ;
    }
    int m=(l+r)>>1;
    build(rt<<1,l,m);
    build(rt<<1|1,m+1,r);
    pushup(rt);
}
inline void pushdown(int rt,int ln,int rn)
{
    if(add[rt])
        add[rt<<1]+=add[rt],
        add[rt<<1|1]+=add[rt],
        tree[rt<<1]+=add[rt]*ln,
        tree[rt<<1|1]+=add[rt]*rn,
        add[rt]=0;
}
inline void change(int rt,int L,int R,int l,int r,int x)
{
    if(L<=l and R>=r)
    {
        add[rt]+=x;
        tree[rt]+=x*(r-l+1);
        return ;
    }
    int m=(l+r)>>1;
    pushdown(rt,m-l+1,r-m);
    if(L<=m)
        change(rt<<1,L,R,l,m,x);
    if(R>m)
        change(rt<<1|1,L,R,m+1,r,x);
    pushup(rt);
}
inline LL getans(int rt,int L,int R,int l,int r)
{
    if(L<=l and R>=r)
        return tree[rt];
    int m=(l+r)>>1;
    pushdown(rt,m-l+1,r-m);
    LL ans=0;
    if(L<=m)
        ans+=getans(rt<<1,L,R,l,m);
    if(R>m)
        ans+=getans(rt<<1|1,L,R,m+1,r);
    return ans;
}

int main()
{
    in(n);in(m);
    for(LL i=1;i<=n;i++)
        inl(a[i]);
    build(1,1,n);
    while(m--)
    {
        int caozuo;
        in(caozuo);
        if(caozuo==1)
        {
            int l,r,x;
            in(l),in(r),in(x);
            change(1,l,r,1,n,x);
        }
        else
        {
            int l,r;
            in(l),in(r);
            printf("%lld\n",getans(1,l,r,1,n));
        }
    }
    return 0;
}

转载于:https://www.cnblogs.com/syhien/p/7786459.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值