-
Notifications
You must be signed in to change notification settings - Fork 1
/
Lazy - Segment Tree
58 lines (58 loc) · 1.31 KB
/
Lazy - Segment Tree
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
const int N = 2e5 + 9;
int a[N];
// 1 base indexing
struct segment_Tree {
#define lc (n << 1)
#define rc ((n << 1) | 1)
vector<int> t, lazy;
segment_Tree() {
t.resize(4 * N);
lazy.resize(4 * N);
}
inline void push(int n, int b, int e) {
if (lazy[n] == 0) return;
t[n] = t[n] + lazy[n] * (e - b + 1);
if (b != e) {
lazy[lc] = lazy[lc] + lazy[n];
lazy[rc] = lazy[rc] + lazy[n];
}
lazy[n] = 0;
}
inline int combine(int a,int b) {
return a + b;
}
inline void pull(int n) {
t[n] = t[lc] + t[rc];
}
void build(int n, int b, int e) {
lazy[n] = 0;
if (b == e) {
t[n] = a[b];
return;
}
int mid = (b + e) >> 1;
build(lc, b, mid);
build(rc, mid + 1, e);
pull(n);
}
void upd(int n, int b, int e, int i, int j, int v) {
push(n, b, e);
if (j < b || e < i) return;
if (i <= b && e <= j) {
lazy[n] = v; //set lazy
push(n, b, e);
return;
}
int mid = (b + e) >> 1;
upd(lc, b, mid, i, j, v);
upd(rc, mid + 1, e, i, j, v);
pull(n);
}
int query(int n, int b, int e, int i, int j) {
push(n, b, e);
if (i > e || b > j) return 0; //return null
if (i <= b && e <= j) return t[n];
int mid = (b + e) >> 1;
return combine(query(lc, b, mid, i, j), query(rc, mid + 1, e, i, j));
}
};