-
Notifications
You must be signed in to change notification settings - Fork 3
/
sparse_segment_tree_class.cpp
85 lines (69 loc) · 1.97 KB
/
sparse_segment_tree_class.cpp
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
// https://leetcode.com/problems/falling-squares
struct segment_tree {
segment_tree(long n) {
int size = 1;
while(size < n) {
size *= 2;
}
this->n = size;
}
// [x, y)
int rmq(long x, long y) {
return rmq(x, y, 0, n);
}
// [x, y)
void add(long x, long y, long val) {
return add(x, y, val, 0, n);
}
private:
unordered_map<long, int> tree;
unordered_map<long, int> lazy;
long n;
int rmq(long x, long y, long l, long r, long id = 1) {
if (!tree.count(id)) return 0;
if (x >= r || y <= l) return 0; // fully out of range
if (x <= l && r <= y) return tree[id]; // fully in range
propagate(id);
int m = (l + r) / 2;
return combine(rmq(x, y, l, m, left(id)), rmq(x, y, m, r, right(id)));
}
void add_lazy(long id, long val) {
tree[id] += val;
lazy[id] += val;
}
void propagate(long id) {
long id_l = left(id);
long id_r = right(id);
if (tree.count(id) && !tree.count(id_l)) {
// create child nodes and copy info forward
tree[id_l] = tree[id];
tree[id_r] = tree[id];
}
else if (lazy[id]) {
add_lazy(id_l, lazy[id]);
add_lazy(id_r, lazy[id]);
}
lazy[id] = 0;
}
void add(long x, long y, long val, long l, long r, long id = 1) {
if (x >= r || y <= l) return; // fully out of range
if (x <= l && r <= y) { // fully in range
add_lazy(id, val);
return;
}
propagate(id);
long m = (l + r) / 2;
add(x, y, val, l, m, left(id));
add(x, y, val, m, r, right(id));
tree[id] = combine(tree[left(id)], tree[right(id)]);
}
long left(long id) {
return 2 * id;
}
long right(long id) {
return 2 * id + 1;
}
long combine(long a, long b) {
return max(a, b);
}
};