forked from Priyansh19077/CP-Templates
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Segment_tree.cpp
84 lines (80 loc) · 2.33 KB
/
Segment_tree.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
// Credits to HealthyUG for the inspiration.
// Segment Tree with Point Updates and Range Queries
// Supports multiple Segment Trees with just a change in the Node and Update
// Very few changes required everytime
template<typename Node, typename Update>
struct SegTree {
vector<Node> tree;
vector<ll> arr; // type may change
int n;
SegTree(int a_len, vector<ll> &a) { // change if type updated
arr = a;
n = a_len;
tree.resize(4 * n); fill(all(tree), Node());
build(0, n - 1, 1);
}
void build(int start, int end, int index) // Never change this
{
if (start == end) {
tree[index] = Node(arr[start]);
return;
}
int mid = (start + end) / 2;
build(start, mid, 2 * index);
build(mid + 1, end, 2 * index + 1);
tree[index].merge(tree[2 * index], tree[2 * index + 1]);
}
void update(int start, int end, int index, int query_index, Update &u) // Never Change this
{
if (start == end) {
u.apply(tree[index]);
return;
}
int mid = (start + end) / 2;
if (mid >= query_index)
update(start, mid, 2 * index, query_index, u);
else
update(mid + 1, end, 2 * index + 1, query_index, u);
tree[index].merge(tree[2 * index], tree[2 * index + 1]);
}
Node query(int start, int end, int index, int left, int right) { // Never change this
if (start > right || end < left)
return Node();
if (start >= left && end <= right)
return tree[index];
int mid = (start + end) / 2;
Node l, r, ans;
l = query(start, mid, 2 * index, left, right);
r = query(mid + 1, end, 2 * index + 1, left, right);
ans.merge(l, r);
return ans;
}
void make_update(int index, ll val) { // pass in as many parameters as required
Update new_update = Update(val); // may change
update(0, n - 1, 1, index, new_update);
}
Node make_query(int left, int right) {
return query(0, n - 1, 1, left, right);
}
};
struct Node1 {
ll val; // may change
Node1() { // Identity element
val = 0; // may change
}
Node1(ll p1) { // Actual Node
val = p1; // may change
}
void merge(Node1 &l, Node1 &r) { // Merge two child nodes
val = l.val ^ r.val; // may change
}
};
struct Update1 {
ll val; // may change
Update1(ll p1) { // Actual Update
val = p1; // may change
}
void apply(Node1 &a) { // apply update to given node
a.val = val; // may change
}
};