线段树1(加法)
#include<iostream>
#include<cstdio>
#define root 1,n,1
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define LL long long
using namespace std;
const int maxn=100001;
LL sum[maxn<<2],add[maxn<<2];
void pushup(int rt){sum[rt]=sum[rt<<1]+sum[rt<<1|1];}
void pushdown(int rt,int len){
if(add[rt]){
add[rt<<1]+=add[rt];
add[rt<<1|1]+=add[rt];
sum[rt<<1]+=add[rt]*(len-(len>>1));
sum[rt<<1|1]+=add[rt]*(len>>1);
add[rt]=0;
}
}
void build(int l,int r,int rt){
sum[rt]=add[rt]=0;
if(l==r){scanf("%lld",&sum[rt]);return ;}
int mid=(l+r)>>1;
build(lson);
build(rson);
pushup(rt);
}
void updata(int L,int R,int c,int l,int r,int rt){
if(L<=l&&r<=R){
add[rt]+=c;sum[rt]+=(LL)c*(r-l+1);return ;
}
pushdown(rt,r-l+1);
int mid=(l+r)>>1;
if(L<=mid)updata(L,R,c,lson);
if(mid<R)updata(L,R,c,rson);
pushup(rt);
}
LL query(int L,int R,int l,int r,int rt){
if(L<=l&&r<=R)return sum[rt];
pushdown(rt,r-l+1);
int mid=(l+r)>>1;
LL res=0;
if(L<=mid)res+=query(L,R,lson);
if(mid<R)res+=query(L,R,rson);
return res;
}
int main(){
int n,Q,opt,a,b,c;
scanf("%d%d",&n,&Q);
build(root);
while(Q--){
scanf("%d%d%d",&opt,&a,&b);
if(opt==1){
scanf("%d",&c);
updata(a,b,c,root);
}else {
printf("%lld\n",query(a,b,root));
}
}
}
线段树2(乘法)
#include<iostream>
#include<cstdio>
#define root 1,n,1
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define LL long long
using namespace std;
const int maxn=100001;
int mod;
LL sum[maxn<<2],add[maxn<<2],mul[maxn<<2];
void pushup(int rt){sum[rt]=sum[rt<<1]+sum[rt<<1|1];}
void pushdown(int rt,int len){
sum[rt<<1]=(sum[rt<<1]*mul[rt]+add[rt]*(len-(len>>1)))%mod;
sum[rt<<1|1]=(sum[rt<<1|1]*mul[rt]+add[rt]*(len>>1))%mod;
mul[rt<<1]=(mul[rt]*mul[rt<<1])%mod;
mul[rt<<1|1]=(mul[rt]*mul[rt<<1|1])%mod;
add[rt<<1]=(add[rt<<1]*mul[rt]+add[rt])%mod;
add[rt<<1|1]=(add[rt<<1|1]*mul[rt]+add[rt])%mod;
add[rt]=0;mul[rt]=1;
}
void build(int l,int r,int rt){
add[rt]=0;mul[rt]=1;
if(l==r){scanf("%lld",&sum[rt]);return ;}
int mid=(l+r)>>1;
build(lson);
build(rson);
pushup(rt);
}
void updata_add(int L,int R,int c,int l,int r,int rt){
if(L<=l&&r<=R){
sum[rt]=(sum[rt]+(r-l+1)*c)%mod;add[rt]=(add[rt]+c)%mod;
return ;
}
pushdown(rt,r-l+1);
int mid=(l+r)>>1;
if(L<=mid)updata_add(L,R,c,lson);
if(mid<R)updata_add(L,R,c,rson);
pushup(rt);
}
void updata_mul(int L,int R,int c,int l,int r,int rt){
if(L<=l&&r<=R){
sum[rt]=(sum[rt]*c)%mod;add[rt]=(add[rt]*c)%mod;mul[rt]=(mul[rt]*c)%mod;
return;
}
pushdown(rt,r-l+1);
int mid=(l+r)>>1;
if(L<=mid)updata_mul(L,R,c,lson);
if(mid<R)updata_mul(L,R,c,rson);
pushup(rt);
}
LL query(int L,int R,int l,int r,int rt){
if(L<=l&&r<=R)return sum[rt];
pushdown(rt,r-l+1);
LL res=0;
int mid=(l+r)>>1;
if(L<=mid)res+=query(L,R,lson);
if(mid<R)res+=query(L,R,rson);
return res%mod;
}
int main(){
int n,Q,opt,a,b,c;
scanf("%d%d%d",&n,&Q,&mod);
build(root);
while(Q--){
scanf("%d%d%d",&opt,&a,&b);
if(opt==1){
scanf("%d",&c);
updata_mul(a,b,c,root);
}
else if(opt==2){
scanf("%d",&c);
updata_add(a,b,c,root);
}
else {
printf("%lld\n",query(a,b,root));
}
}
}