首页 > 其他 > 详细

线段树

时间:2019-08-11 17:15:29      阅读:93      评论:0      收藏:0      [点我收藏+]

参考:线段树

模板题:线段树模板

变量

const int maxn=1e5+5;
int d[maxn<<2],a[maxn],laz[maxn<<2];
    /*d[]保存区间和 a[]保存原始数据 laz[]懒惰标记为*/

建树

void build(int s,int t,int p)
{
    if(s==t)
    {
        d[p]=a[s];
        return ;
    }
    int m=(s+t)>>1;
    build(s,m,p<<1),build(m+1,t,p<<1|1);
    d[p]=d[p<<1]+d[p<<1|1];
}

下传懒惰标记

void pushdown(int s,int t,int p)
{
    int m=(s+t)>>1;
    d[p<<1]+=laz[p]*(m-s+1),d[p<<1|1]+=laz[p]*(t-m);
    laz[p<<1]+=laz[p],laz[p<<1|1]+=laz[p];
    laz[p]=0;
}

区间更新

void update(int l,int r,int c,int s,int t,int p)
{
    if(l<=s&&t<=r)
    {
        d[p]+=(t-s+1)*c,laz[p]+=c;
        return ;
    }
    int m=(s+t)>>1;
    if(laz[p]) pushdown(s,t,p);
    if(l<=m) update(l,r,c,s,m,p<<1);
    if(r>m) update(l,r,c,m+1,t,p<<1|1);
    d[p]=d[p<<1]+d[p<<1|1];
}

区间修改

int getsum(int l,int r,int s,int t,int p)
{
    if(l<=s&&t<=r) return d[p];
    int m=(s+t)>>1;
    if(laz[p]) pushdown(s,t,p);
    int sum=0;
    if(l<=m) sum+=getsum(l,r,s,m,p<<1);
    if(r>m) sum+=getsum(l,r,m+1,t,p<<1|1);
    return sum;
}

线段树

原文:https://www.cnblogs.com/CADCADCAD/p/11335276.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!