题意:nlogn实现区间加、区间乘、区间求和(都要求取模)
题解:
只要记住一句话:(x+a)*b=x*b+a*b,先乘后加,乘法标记管两个(sum,add),加法标记管一个(sum)。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
#define root 1,1,n
#define lson rt<<1,l,mid
#define rson rt<<1|1,mid+1,r
typedef long long ll;
const int N=1e5+4;
int n,m;
ll a[N],mod,sum[N<<2],add[N<<2],mul[N<<2];
inline ll read() {
ll x=0,f=1;char c=getchar();
while (c<'0'||c>'9') {if (c=='-') f=-1;c=getchar();}
while (c>='0'&&c<='9') x=x*10+c-'0',c=getchar();
return x*f;
}
void build(int rt,int l,int r) {
add[rt]=0,mul[rt]=1;
if (l==r) {sum[rt]=a[l];return ;}
int mid=l+r>>1;
build(lson);
build(rson);
(sum[rt]=sum[rt<<1]+sum[rt<<1|1])%=mod;
}
inline void pushdown(int rt,int len) {
int lf=len-(len>>1),rg=len>>1;
if (mul[rt]^1) {
(add[rt<<1]*=mul[rt])%=mod,(mul[rt<<1]*=mul[rt])%=mod,(sum[rt<<1]*=mul[rt])%=mod;
(add[rt<<1|1]*=mul[rt])%=mod,(mul[rt<<1|1]*=mul[rt])%=mod,(sum[rt<<1|1]*=mul[rt])%=mod;
mul[rt]=1;
}
if (add[rt]) {
(add[rt<<1]+=add[rt])%=mod,(sum[rt<<1]+=lf*add[rt]%mod)%=mod;
(add[rt<<1|1]+=add[rt])%=mod,(sum[rt<<1|1]+=rg*add[rt]%mod)%=mod;
add[rt]=0;
}
}
void modify(int rt,int l,int r,int L,int R,ll v,int opt) {
if (L<=l&&r<=R) {
if (opt&1) (add[rt]*=v)%=mod,(mul[rt]*=v)%=mod,(sum[rt]*=v)%=mod;
else (add[rt]+=v)%=mod,(sum[rt]+=(r-l+1)*v%mod)%=mod;
return ;
}
pushdown(rt,r-l+1);
int mid=l+r>>1;
if (L<=mid) modify(lson,L,R,v,opt);
if (mid<R) modify(rson,L,R,v,opt);
(sum[rt]=sum[rt<<1]+sum[rt<<1|1])%=mod;
}
ll query(int rt,int l,int r,int L,int R) {
if (L<=l&&r<=R) return sum[rt];
pushdown(rt,r-l+1);
int mid=l+r>>1;
ll ret=0;
if (L<=mid) (ret+=query(lson,L,R))%=mod;
if (mid<R) (ret+=query(rson,L,R))%=mod;
return ret;
}
int main() {
// freopen("P3373.in","r",stdin);
n=read(),m=read(),mod=read();
for (register int i=1;i<=n;++i) a[i]=read()%mod;
build(root);
for (register int t=0;t<m;++t) {
int opt=read();
switch (opt) {
case 1:{
int x=read(),y=read();
ll v=read();
modify(root,x,y,v,1);
break;
}
case 2:{
int x=read(),y=read();
ll v=read();
modify(root,x,y,v,2);
break;
}
case 3:{
int x=read(),y=read();
printf("%lld\n",query(root,x,y));
break;
}
}
}
return 0;
}