思路:线段树,懒惰标记下传需注意
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const LL maxn = 100000 + 100;
LL n,a[maxn],p;
struct segment_tree{
LL l,r,laz1,laz2,sum;
segment_tree( ){
l = 0;
r = 0;
laz1 = 0;
laz2 = 1;
sum = 0;
}
#define r(x) tree[x].r
#define l(x) tree[x].l
#define laz1(x) tree[x].laz1
#define laz2(x) tree[x].laz2
#define sum(x) tree[x].sum
#define lc x<<1
#define rc (x<<1) + 1
}tree[5 * maxn];
void update( LL x ){
sum(x) = (sum(lc) + sum(rc))%p;
}
void build( LL x,LL l,LL r ){
l(x) = l;
r(x) = r;
if( l == r ){
sum(x) = a[l]%p;
return;
}
LL mid = l + r >> 1;
build( lc, l,mid );
build( rc,mid+1,r );
update( x );
}
void spread1(LL x){
laz1( lc ) = (laz1( lc ) + laz1(x) ) % p;
sum( lc ) = (sum( lc ) + laz1(x) *( r(lc) - l(lc)+1 ) )% p;
laz1(rc) = ( laz1(rc) + laz1(x) ) % p;
sum( rc ) = (sum( rc ) + laz1(x) *( r(rc) - l(rc) + 1 )) %p;
laz1(x) = 0;
}
void spread2( LL x ){
laz2( lc ) = (laz2( lc ) * laz2(x) )%p;
laz1( lc ) = ( laz1(lc) * laz2(x) ) % p;
sum( lc ) = (sum( lc ) * laz2( x ) ) % p;
laz2( rc ) = (laz2( rc ) * laz2(x) ) % p;
laz1( rc ) = ( laz1(rc) * laz2(x) ) % p;
sum( rc ) = (sum( rc ) * laz2( x ) ) %p;
laz2(x) = 1;
}
LL ask( LL x,LL l,LL r ){
if( l <= l(x) && r >= r(x) ){
return sum(x);
}
if( laz2(x) != 1 ) spread2(x);
if(laz1(x) ) spread1(x);
LL re = 0;
LL mid = l(x) + r(x) >> 1 ;
if( l <= mid ){
re = (re + ask(lc,l,r ))%p;
}
if( r > mid ){
re = (re + ask(rc,l,r))%p;
}
return re;
}
void change1(LL x,LL l,LL r,LL v ){
if( l <= l(x) && r >= r(x) ){
sum(x) = (sum(x)+ (r(x) - l(x) + 1) * v) %p;
laz1(x) = (laz1(x) + v) %p;
return;
}
if( laz2(x) != 1 ) spread2(x);
if(laz1(x) ) spread1(x);
LL mid = l(x) + r(x) >> 1;
if( l <= mid )change1(lc,l,r,v);
if( r > mid )change1(rc,l,r,v);
update(x);
}
void change2( LL x,LL l,LL r,LL v ){
if( l <= l(x) && r >= r(x) ){
sum(x) = (sum(x)* v)%p;
laz1(x) = (laz1(x) * v) % p;
laz2(x) = (laz2(x) * v) %p;
return;
}
if( laz2(x) != 1 ) spread2(x);
if(laz1(x) ) spread1(x);
LL mid = l(x) + r(x) >> 1;
if( l <= mid )change2( lc,l,r,v );
if( r > mid )change2( rc,l,r,v );
update(x);
}
int main()
{
LL q,f,x,y,v;
scanf("%lld%lld",&n,&p);
for( LL i = 1;i <= n;i++ ){
scanf("%lld",&a[i]);
}
build(1,1,n);
scanf("%lld",&q);
for( LL i = 1;i <= q;i++ ){
scanf("%lld",&f);
if( f == 1 ){
scanf("%lld%lld%lld",&x,&y,&v);
change2(1,x,y,v);
}else if( f == 2 ){
scanf("%lld%lld%lld",&x,&y,&v);
change1(1,x,y,v);
}else{
scanf("%lld%lld",&x,&y);
printf("%lld\n",ask( 1,x,y ));
}
}
return 0;
}