线段树: 维护序列
本题每个节点存在两个懒标记add
和mul
用来更新区间节点的答案.
我们把区间的值sum
看成sum = a * mul + add
对于modify
操作
如果我们需要对一段区间的所有数乘上d
, 相当于:
sum = a * mul * d + add * d
, 即, 我们只用修改对应mul
和add
的值:
mul = mul * d, add = add * d
.
如果我们需要对一段区间的所有数加上d
,相当于:
sum = a * mul + add + d
, 即, 我们只需要修改add
值:
add = add + d
.
#include <bits/stdc++.h>
using namespace std;
#define IO ios::sync_with_stdio(false);cin.tie(0); cout.tie(0);
inline int lowbit(int x) { return x & (-x); }
#define ll long long
#define ull unsigned long long
#define pb push_back
#define PII pair<int, int>
#define VIT vector<int>
#define x first
#define y second
#define inf 0x3f3f3f3f
const int N = 1e5 + 10;
int n, p;
int w[N];
struct Node {
int l, r;
ll sum, add, mul;
}tr[4 * N];
void pushup(int u) {
tr[u].sum = (tr[u << 1].sum + tr[u << 1 | 1].sum) % p;
}
void build(int u, int l, int r) {
if (l == r) tr[u] = {l, r, w[r], 0, 1};
else {
tr[u] = {l, r, 0, 0, 1};
int mid = l + r >> 1;
build(u << 1, l, mid), build(u << 1 | 1, mid + 1, r);
pushup(u);
}
}
void eval(Node &t, int add, int mul) {
t.sum = ((ll)t.sum * mul + (ll)(t.r - t.l + 1) * add) % p;
t.mul = (ll)t.mul * mul % p;
t.add = ((ll)t.add * mul + add) % p;
}
void pushdown(int u) {
eval(tr[u << 1], tr[u].add, tr[u].mul); // 父节点更新左儿子
eval(tr[u << 1 | 1], tr[u].add, tr[u].mul); // 父节点更新右儿子
tr[u].add = 0, tr[u].mul = 1;
}
void modify(int u, int l, int r, int add, int mul) {
if (tr[u].l >= l && tr[u].r <= r) eval(tr[u], add, mul);
else {
pushdown(u);
int mid = tr[u].l + tr[u].r >> 1;
if (l <= mid) modify(u << 1, l, r, add, mul);
if (r > mid) modify(u << 1 | 1, l, r, add, mul);
pushup(u);
}
}
int query(int u, int l, int r) {
if (tr[u].l >= l && tr[u].r <= r) return tr[u].sum;
pushdown(u);
int mid = tr[u].l + tr[u].r >> 1;
int sum = 0;
if (l <= mid) sum = query(u << 1, l, r);
if (r > mid) sum = (sum + query(u << 1 | 1, l, r)) % p;
return sum;
}
int main() {
//freopen("in.txt", "r", stdin);
IO;
cin >> n >> p;
for (int i = 1; i <= n; ++i) cin >> w[i];
build(1, 1, n);
int m;
cin >> m;
while (m--) {
int t, l, r, d;
cin >> t >> l >> r;
if (t == 1) {
cin >> d;
modify(1, l, r, 0, d);
} else if (t == 2) {
cin >> d;
modify(1, l, r, d, 1);
} else cout << query(1, l, r) << '\n';
}
return 0;
}