维护一个长度为 N 的序列,支持区间加和、区间乘积、查询区间和操作。
代码如下
#include <bits/stdc++.h>
using namespace std;
const int maxn=1e5+10;
inline int read(){
int x=0,f=1;char ch;
do{ch=getchar();if(ch=='-')f=-1;}while(!isdigit(ch));
do{x=x*10+ch-'0';ch=getchar();}while(isdigit(ch));
return f*x;
}
int n,m,a[maxn];long long mod;
struct node{
#define ls(x) t[x].lc
#define rs(x) t[x].rc
int lc,rc;
long long sum,stag,mtag;
}t[maxn<<1];
int tot,root;
inline void pushup(int o){t[o].sum=(t[ls(o)].sum+t[rs(o)].sum)%mod;}
inline void pushdown(int o,int l,int r){
int mid=l+r>>1;
t[ls(o)].sum=(t[ls(o)].sum*t[o].mtag%mod+(mid-l+1)*t[o].stag%mod)%mod;
t[ls(o)].mtag=t[ls(o)].mtag*t[o].mtag%mod;
t[ls(o)].stag=(t[ls(o)].stag*t[o].mtag%mod+t[o].stag)%mod;
t[rs(o)].sum=(t[rs(o)].sum*t[o].mtag%mod+(r-mid)*t[o].stag%mod)%mod;
t[rs(o)].mtag=t[rs(o)].mtag*t[o].mtag%mod;
t[rs(o)].stag=(t[rs(o)].stag*t[o].mtag%mod+t[o].stag)%mod;
t[o].stag=0,t[o].mtag=1;
}
int build(int l,int r){
int o=++tot;
t[o].mtag=1;
if(l==r){t[o].sum=a[l];return o;}
int mid=l+r>>1;
ls(o)=build(l,mid),rs(o)=build(mid+1,r);
pushup(o);
return o;
}
void modify(int o,int l,int r,int x,int y,long long val,int mode){//1->add 2->mul
if(l==x&&r==y){
if(mode==1)t[o].sum=(t[o].sum+(r-l+1)*val)%mod,t[o].stag=(t[o].stag+val)%mod;
else t[o].sum=t[o].sum*val%mod,t[o].mtag=t[o].mtag*val%mod,t[o].stag=t[o].stag*val%mod;
return;
}
int mid=l+r>>1;
pushdown(o,l,r);
if(y<=mid)modify(ls(o),l,mid,x,y,val,mode);
else if(x>mid)modify(rs(o),mid+1,r,x,y,val,mode);
else modify(ls(o),l,mid,x,mid,val,mode),modify(rs(o),mid+1,r,mid+1,y,val,mode);
pushup(o);
}
long long query(int o,int l,int r,int x,int y){
if(l==x&&r==y)return t[o].sum;
int mid=l+r>>1;
pushdown(o,l,r);
if(y<=mid)return query(ls(o),l,mid,x,y);
else if(x>mid)return query(rs(o),mid+1,r,x,y);
else return query(ls(o),l,mid,x,mid)+query(rs(o),mid+1,r,mid+1,y);
}
int main(){
n=read(),mod=read();
for(int i=1;i<=n;i++)a[i]=read();
root=build(1,n);
m=read();
while(m--){
int opt=read();
if(opt==1){
int l=read(),r=read(),val=read();
modify(root,1,n,l,r,val,2);
}else if(opt==2){
int l=read(),r=read(),val=read();
modify(root,1,n,l,r,val,1);
}else{
int l=read(),r=read();
printf("%lld
",query(root,1,n,l,r)%mod);
}
}
return 0;
}