给一个数列,进行三种操作:
- 某区间每个数 × x \times x ×x
- 某区间每个数 + x +x +x
- 求区间和
和线段树模板1相比,多了一个乘法操作。要先乘后加。还有注意步步取模…
代码如下:
#include<iostream>
#include<cstdio>
#define lc(p) ((p)<<1)
#define rc(p) (((p)<<1)|1)
#define MAXN 100005
using namespace std;
typedef long long ll;
int n,m,MOD,x,y,t;
ll a[MAXN],t1[MAXN<<2],t2[MAXN<<2],res[MAXN<<2],k;
void pushup(int p){res[p]=(res[lc(p)]+res[rc(p)])%MOD;}
void build(int l,int r,int p){
t1[p]=1;t2[p]=0;
if(l==r){res[p]=a[l]%MOD;return;}
int mid=l+(r-l)/2;
build(l,mid,lc(p));build(mid+1,r,rc(p));
pushup(p);
}
void f(int l,int r,int p,ll k1,ll k2){
res[p]=(res[p]*k1%MOD+k2*(r-l+1)%MOD)%MOD;
t1[p]=k1*t1[p]%MOD;t2[p]=(t2[p]*k1%MOD+k2)%MOD;
}
void pushdown(int l,int r,int p){
int mid=l+(r-l)/2;
f(l,mid,lc(p),t1[p],t2[p]);f(mid+1,r,rc(p),t1[p],t2[p]);
t1[p]=1;t2[p]=0;
}
void upd1(int x,int y,int l,int r,int p,ll k){
if(x<=l&&r<=y){res[p]=res[p]*k%MOD;t1[p]=k*t1[p]%MOD;t2[p]=k*t2[p]%MOD;return;}
pushdown(l,r,p);
int mid=l+(r-l)/2;
if(x<=mid)upd1(x,y,l,mid,lc(p),k);
if(y>mid)upd1(x,y,mid+1,r,rc(p),k);
pushup(p);
}
void upd2(int x,int y,int l,int r,int p,ll k){
if(x<=l&&r<=y){res[p]=(res[p]+(r-l+1)*k%MOD)%MOD;t2[p]=(k+t2[p])%MOD;return;}
pushdown(l,r,p);
int mid=l+(r-l)/2;
if(x<=mid)upd2(x,y,l,mid,lc(p),k);
if(y>mid)upd2(x,y,mid+1,r,rc(p),k);
pushup(p);
}
ll query(int x,int y,int l,int r,int p){
if(x<=l&&r<=y)return res[p]%MOD;
pushdown(l,r,p);
int mid=l+(r-l)/2;ll res=0;
if(x<=mid)res+=query(x,y,l,mid,lc(p));res%=MOD;
if(y>mid)res+=query(x,y,mid+1,r,rc(p));
return res%MOD;
}
int main(){
#ifdef WINE
freopen("data.in","r",stdin);
#endif
scanf("%d%d%d",&n,&m,&MOD);
for(int i=1;i<=n;i++)scanf("%lld",&a[i]);
build(1,n,1);
while(m--){
scanf("%d%d%d",&t,&x,&y);
if(t!=3)scanf("%lld",&k);
if(t==1)upd1(x,y,1,n,1,k);
if(t==2)upd2(x,y,1,n,1,k);
if(t==3)printf("%lld\n",query(x,y,1,n,1));
}
return 0;
}