forked from Priyansh19077/CP-Templates
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSparse_Table.cpp
65 lines (64 loc) · 1.42 KB
/
Sparse_Table.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
// O(1) for idempotent O(logN) for general
// Supports multiple sparse tables with minor change in Node
template<typename Node>
struct SparseTable {
vector<vector<Node>> table;
vector<ll> logValues;
int n;
int maxLog;
vector<ll> a;
SparseTable(int n1, vector<ll> &arr) {
n = n1;
a = arr;
table.resize(n);
logValues.resize(n + 1);
maxLog = log2(n);
logValues[1] = 0;
for (int i = 2; i <= n; i++) {
logValues[i] = logValues[i / 2] + 1;
}
for (int i = 0; i < n; i++) {
table[i].resize(maxLog + 1);
fill(all(table[i]), Node());
}
build();
}
void build() {
for (int i = 0; i < n; i++) {
table[i][0] = Node(a[i]);
}
for (int i = 1; i <= maxLog; i++) {
for (int j = 0; (j + (1 << i)) <= n; j++) {
table[j][i].merge(table[j][i - 1], table[j + (1 << (i - 1))][i - 1]);
}
}
}
Node queryNormal(int left, int right) {
Node ans = Node();
for (int j = logValues[right - left + 1]; j >= 0; j--) {
if ((1 << j) <= right - left + 1) {
ans.merge(ans, table[left][j]);
left += (1 << j);
}
}
return ans;
}
Node queryIdempotent(int left, int right) {
int j = logValues[right - left + 1];
Node ans = Node();
ans.merge(table[left][j], table[right - (1 << j) + 1][j]);
return ans;
}
};
struct Node1 {
ll val; // store more info if required
Node1() { // Identity Element
val = 0;
}
Node1(ll v) {
val = v;
}
void merge(Node1 &l, Node1 &r) {
val = l.val ^ r.val;
}
};