首页 > 其他 > 详细

线段树1

时间:2020-07-05 16:20:40      阅读:37      评论:0      收藏:0      [点我收藏+]
#include<cstdio>

using namespace std;

const int maxn=1e5;

typedef long long int ll;

ll a[maxn];

struct node{
    int v;
    int l,r;
    int tag;
    node *ls,*rs;
    
    inline bool maketag(const ll w){
        v+=(r-l+1)*w;
        tag+=w;
    }
    
    inline void pushup(){
        v=ls->v+rs->v;
    }
    inline void pushdown(){
        if(tag==0)
        return;
        ls->maketag(tag);
        rs->maketag(tag);
        tag=0;
    }
    
build(const int L,const int R){
    l=L;
    r=R;
    if(l==r){
        tag=0;
        v=a[l];
        ls=rs=NULL;
    }else{
        tag=0;
        int M=(l+r)>>1;
        ls=new node (l,M);
        rs=new node (M+1,r);
        pushup();
    }
    
}
    
    inline bool inrange(const int L,const int R){
        return (l<=L)&&(r<=R);
    }
    
    inline bool outrange(const int L,const int R){
        return (l>R)||(r<L);
    }
    
    void upd(const int L,const int R,const ll w){
        if(inrange(L,R)){
            maketag(tag);
        }else if(!outrange(L,R)){
            pushdown();
            ls->upd(L,R,w);
            rs->upd(L,R,w);
            pushup();
        }
    }
    
    ll qry(const int L,const int R){
        if(inrange(L,R))
        return v;
        if(outofrange(L,R))
        return 0;
        pushdown();
        return ls->qry(L,R)+rs->qry(L,R);
        
    }
    
};

int main()
{
    scanf("%d%d",&n,&q);
    
    for(int i=1;i<=n;i++)
    scanf("%lld",a+i);
    
    node *rot=new node(1,n);
    
    for(ll o,x,y,z;q;q--)
    {
        scanf("%lld%lld%lld",&o,&x,&y);
        
        if(o==1)
        {
            scanf("%lld",&z);
            rot->upd(x,y,z);
        }else{
            printf("%lld\n",rot->qry(x,y));
        }
    }    
    
    return 0;
    
}

 

线段树1

原文:https://www.cnblogs.com/dairuizhe/p/13246283.html

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