-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsparse_table.cpp
More file actions
30 lines (27 loc) · 814 Bytes
/
sparse_table.cpp
File metadata and controls
30 lines (27 loc) · 814 Bytes
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
template<class T>
class Min{
public:
T operator()(const T &a, const T &b) const{
return min(a,b);
}
};
template <class T, class Op>
class SparseTable {
public:
explicit SparseTable(const std::vector<T>& arr) {
lookup.resize(arr.size(), std::vector<T>(std::log2(arr.size()) + 1));
for (unsigned i = 0; i < arr.size(); i++) { lookup[i][0] = arr[i]; }
for (unsigned j = 1; (1u << j) <= arr.size(); j++) {
for (unsigned i = 0; i + (1u << j) - 1 < arr.size(); i++) {
lookup[i][j] = op(lookup[i][j - 1], lookup[i + (1u << (j - 1))][j - 1]);
}
}
}
T query(int left, int right) const {
unsigned j = std::log2(right - left + 1);
return op(lookup[left][j], lookup[right - (1u << j) + 1][j]);
}
private:
Op op;
std::vector<std::vector<T> > lookup;
};