题解:[AHOI2009] 维护序列

洛谷P2023

Posted by TH911 on December 14, 2024

题目传送门

线段树 2 几乎一模一样,直接放出代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
//#include<bits/stdc++.h>
#include<algorithm> 
#include<iostream>
#include<cstring>
#include<iomanip>
#include<cstdio>
#include<string>
#include<vector>
#include<cmath>
#include<ctime>
#include<deque>
#include<queue>
#include<stack>
#include<list>
using namespace std;
#define int long long
const int N=1e5; 
struct node{
	//tag1:乘法标记,tag2:加法标记 
	int l,r,value,tag1,tag2;
}t[4*N+1];
int n,q,M,a[N+1];
inline void up(int p){
	t[p].value=t[p*2].value+t[p*2+1].value;
	t[p].value%=M;
}
void build(int p,int l,int r){
	t[p].l=l,t[p].r=r,t[p].tag1=1;
	if(l==r)t[p].value=a[l]%M;
	else{
		int mid=(l+r)/2;
		build(p*2,l,mid);
		build(p*2+1,mid+1,r);
		up(p);
	}
}
inline int size(int p){
	return t[p].r-t[p].l+1;
}
inline void down(int p){
	t[p*2].value=(t[p*2].value * t[p].tag1 + size(p*2)*t[p].tag2)%M;
	t[p*2].tag1=t[p*2].tag1*t[p].tag1%M;
	t[p*2].tag2=(t[p*2].tag2*t[p].tag1+t[p].tag2)%M;
	
	t[p*2+1].value=(t[p*2+1].value * t[p].tag1 + size(p*2+1)*t[p].tag2)%M;
	t[p*2+1].tag1=t[p*2+1].tag1*t[p].tag1%M;
	t[p*2+1].tag2=(t[p*2+1].tag2*t[p].tag1+t[p].tag2)%M;
	
	t[p].tag1=1;
	t[p].tag2=0;
}
//乘法 
void solve1(int p,int l,int r,int k){
	if(l<=t[p].l&&t[p].r<=r){
		t[p].value*=k;
		t[p].value%=M;
		t[p].tag1*=k;
		t[p].tag1%=M;
		t[p].tag2*=k;
		t[p].tag2%=M;
	}else{
		down(p);
		int mid=(t[p].l+t[p].r)/2;
		if(l<=mid)solve1(p*2,l,r,k);
		if(mid<r)solve1(p*2+1,l,r,k);
		up(p);
	}
}
//加法 
void solve2(int p,int l,int r,int k){
	if(l<=t[p].l&&t[p].r<=r){
		t[p].value+=size(p)*k;
		t[p].value%=M;
		t[p].tag2+=k;
		t[p].tag2%=M;
	}else{
		down(p);
		int mid=(t[p].l+t[p].r)/2;
		if(l<=mid)solve2(p*2,l,r,k);
		if(mid<r)solve2(p*2+1,l,r,k);
		up(p);
	}
}
int query(int p,int l,int r){
	if(l<=t[p].l&&t[p].r<=r)return t[p].value;
	down(p);
	int mid=(t[p].l+t[p].r)/2,ans=0;
	if(l<=mid)ans+=query(p*2,l,r);
	ans%=M;
	if(mid<r)ans+=query(p*2+1,l,r);
	ans%=M;
	return ans;
}
main(){
//	freopen("test.in","r",stdin);
//	freopen("test.out","w",stdout);
	
	scanf("%lld%lld",&n,&M);
	for(int i=1;i<=n;i++)scanf("%lld",a+i);
	build(1,1,n); 
	scanf("%lld",&q);
	while(q--){ 
		int op,x,y,k;
		scanf("%lld %lld %lld",&op,&x,&y);
		switch(op){
			case 1:
				scanf("%lld",&k);
				solve1(1,x,y,k%M);
				break;
			case 2:
				scanf("%lld",&k);
				solve2(1,x,y,k%M);
				break;
			case 3:
				printf("%lld\n",query(1,x,y));
				break;
		} 
	} 
	
	/*fclose(stdin);
	fclose(stdout);*/
	return 0;
}