Luogu P3372 【模板】线段树 1 (标记永久化)

题目描述

https://www.luogu.com.cn/problem/P3372

Solution

最基础的标记永久化的做法

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
#include <iostream>
#include <cstdio>
#define maxn 100010
#define ll long long
using namespace std;

int n, m, a[maxn];

#define lc i << 1
#define rc i << 1 | 1
struct seg {
ll v, add;
} T[maxn * 4];
void build(int i, int l, int r) {
if (l == r) return (void) (T[i].v = a[l]);
int m = l + r >> 1;
build(lc, l, m); build(rc, m + 1, r);
T[i].v = T[lc].v + T[rc].v;
}

void update(int i, int l, int r, int L, int R, int v) {
if (l > R || r < L) return ;
T[i].v += (ll) (min(r, R) - max(L, l) + 1) * v;
if (L <= l && r <= R) return (void) (T[i].add += v);
int m = l + r >> 1;
update(lc, l, m, L, R, v); update(rc, m + 1, r, L, R, v);
}

ll query(int i, int l, int r, int L, int R, ll add) {
if (l > R || r < L) return 0;
if (L <= l && r <= R) return T[i].v + (r - l + 1) * add;
int m = l + r >> 1;
return query(lc, l, m, L, R, add + T[i].add) + query(rc, m + 1, r, L, R, add + T[i].add);
}

inline void solve_1() {
int l, r, v; scanf("%d%d%d", &l, &r, &v);
update(1, 1, n, l, r, v);
}

inline void solve_2() {
int l, r; scanf("%d%d", &l, &r);
printf("%lld\n", query(1, 1, n, l, r, 0));
}

int main() {
cin >> n >> m;
for (int i = 1; i <= n; ++i) scanf("%d", &a[i]);
build(1, 1, n);
for (int i = 1; i <= m; ++i) {
int opt; scanf("%d", &opt);
switch (opt) {
case 1 : solve_1(); break;
case 2 : solve_2(); break;
}
}
return 0;
}