bzoj 1798: [Ahoi2009]Seq 维护序列seq 线段树 区间乘法区间加法 区间求和

题目链接:

http://www.lydsy.com/JudgeOnline/problem.php?id=1798

题意:

题解:

线段树,区间乘法+区间加法,都扔给一个updata就好

代码:

#include 
using namespace std;
typedef long long ll;
#define MS(a) memset(a,0,sizeof(a))
#define MP make_pair
#define PB push_back
const int INF = 0x3f3f3f3f;
const ll INFLL = 0x3f3f3f3f3f3f3f3fLL;
inline ll read(){
    ll x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
//////////////////////////////////////////////////////////////////////////
const int maxn = 1e5+10;

ll a[maxn],mod,ans[maxn];

struct node{
    int l,r;
    ll sum,add,mul,lazy;
    void update(int a,int m,int len){
        add = ((ll)(add*m+a))%mod;
        mul = ((ll)(m*mul))%mod;
        sum = ((ll)((ll)sum*m+(ll)len*a))%mod;
    }
}tree[maxn<<2];

void pushup(int rt){
    tree[rt].sum = (tree[rt<<1].sum + tree[rt<<1|1].sum) % mod;
}

void pushdown(int rt,int len){
    if(tree[rt].add!=0 || tree[rt].mul!=1){
        tree[rt<<1].update(tree[rt].add,tree[rt].mul,len-(len>>1));
        tree[rt<<1|1].update(tree[rt].add,tree[rt].mul,len>>1);
        tree[rt].add = 0; tree[rt].mul = 1;
    }
}


void build(int rt,int l,int r){
    tree[rt].l = l, tree[rt].r = r;
    tree[rt].add = 0, tree[rt].mul = 1;
    if(l == r) {
        tree[rt].sum = a[l];
        return ;
    }
    int mid = (l+r)/2;
    build(rt<<1,l,mid);
    build(rt<<1|1,mid+1,r);
    pushup(rt);
}

void update(int rt,int l,int r,int add,int mul){
    int L = tree[rt].l, R = tree[rt].r;
    if(l<=L && R<=r){
        tree[rt].update(add,mul,R-L+1);
        return ;
    }
    pushdown(rt,R-L+1);
    int mid = (L+R)/2;
    if(l<=mid) update(rt<<1,l,r,add,mul);
    if(r>mid) update(rt<<1|1,l,r,add,mul);
    pushup(rt);
}

ll query(int rt,int l,int r){
    int L = tree[rt].l, R = tree[rt].r;
    if(l<=L && R<=r)
        return tree[rt].sum;
    else{
        ll ans = 0;
        pushdown(rt,R-L+1);
        int mid = (L+R)/2;
        if(l<=mid) ans = ((ll)(ans+query(rt<<1,l,r)))%mod;
        if(r>mid) ans = ((ll)(ans+query(rt<<1|1,l,r)))%mod;
        pushup(rt);
        return ans;
    }
}

int main(){
    int n=read(); 
    mod = read();
    for(int i=1; i<=n; i++){
        a[i] = read();
    }
    build(1,1,n);
    int m = read();
    while(m--){
        int op = read();
        if(op == 1){
            int a=read(),b=read(),x=read();
            update(1,a,b,0,x);
        }else if(op == 2){
            int a=read(),b=read(),add=read();
            update(1,a,b,add,1);
        }else{
            int a=read(),b=read();
            printf("%lld\n",query(1,a,b)%mod);
        }
    }

    return 0;
}

你可能感兴趣的:(====数据结构====,线段树,bzoj)