【bzoj1798】【AHOI2009】维护序列

练一下线段树模板,区间乘法。

#include<bits/stdc++.h>
#define lson (o<<1)
#define rson (o<<1|1)
const int N=100010;
using namespace std;
typedef long long ll;
ll n,m,yql;
ll a[N];
struct Segment_Tree{
    ll sumv[N<<2],addv[N<<2],mulv[N<<2];
    inline void pushup(int o){sumv[o]=(sumv[lson]+sumv[rson])%yql;}
    inline void pushdown(int o,int l,int r){
        if(mulv[o]==1&&addv[o]==0)return;
        int mid=(l+r)>>1;
        mulv[lson]=mulv[lson]*mulv[o]%yql;
        mulv[rson]=mulv[rson]*mulv[o]%yql;
        addv[lson]=(addv[lson]*mulv[o]%yql+addv[o])%yql;
        addv[rson]=(addv[rson]*mulv[o]%yql+addv[o])%yql;
        sumv[lson]=((sumv[lson]*mulv[o])%yql+addv[o]*1LL*(mid-l+1)%yql)%yql;
        sumv[rson]=((sumv[rson]*mulv[o])%yql+addv[o]*1LL*(r-mid)%yql)%yql;
        mulv[o]=1;addv[o]=0;
    }
    inline void build(int o,int l,int r){
        mulv[o]=1;addv[o]=0;sumv[o]=0;
        if(l==r){sumv[o]=a[l];return;}
        int mid=(l+r)>>1;
        build(lson,l,mid);build(rson,mid+1,r);
        pushup(o);
    }
    inline void mul(int o,int l,int r,int ql,int qr,int v){
        if(ql<=l&&r<=qr){
            mulv[o]=mulv[o]*1LL*v%yql;
            addv[o]=addv[o]*1LL*v%yql;
            sumv[o]=sumv[o]*1LL*v%yql;
            return;
        }
        pushdown(o,l,r);
        int mid=(l+r)>>1;
        if(ql<=mid)mul(lson,l,mid,ql,qr,v);
        if(qr>mid)mul(rson,mid+1,r,ql,qr,v);
        pushup(o);
    }
    inline void add(int o,int l,int r,int ql,int qr,int v){
        if(ql<=l&&r<=qr){
            addv[o]=(addv[o]+1LL*v)%yql;
            sumv[o]=(sumv[o]+1LL*(r-l+1)*v%yql)%yql;
            return;
        }
        pushdown(o,l,r);
        int mid=(l+r)>>1;
        if(ql<=mid)add(lson,l,mid,ql,qr,v);
        if(qr>mid)add(rson,mid+1,r,ql,qr,v);
        pushup(o);
    }
    inline ll querysum(int o,int l,int r,int ql,int qr){
        if(ql<=l&&r<=qr)return sumv[o];
        int mid=(l+r)>>1;ll ans=0;
        pushdown(o,l,r);
        if(ql<=mid)ans+=querysum(lson,l,mid,ql,qr),ans%=yql;
        if(qr>mid)ans+=querysum(rson,mid+1,r,ql,qr),ans%=yql;
        return ans;
    }
}T;
inline ll read(){
    ll f=1,x=0;char ch;
    do{ch=getchar();if(ch=='-')f=-1;}while(ch<'0'||ch>'9');
    do{x=x*10+ch-'0';ch=getchar();}while(ch>='0'&&ch<='9');
    return f*x;
}
int main(){
    n=read();yql=read();
    for(int i=1;i<=n;i++)a[i]=read();
    T.build(1,1,n);
    m=read();
    while(m--){
        ll opt=read();
        if(opt==1){int l=read(),r=read(),x=read();T.mul(1,1,n,l,r,x);}
        if(opt==2){int l=read(),r=read(),x=read();T.add(1,1,n,l,r,x);}
        if(opt==3){int l=read(),r=read();printf("%lld\n",T.querysum(1,1,n,l,r));}
    }
}

 

posted @ 2017-08-14 21:30  zcysky  阅读(253)  评论(0编辑  收藏  举报