-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathSparseTable.cpp
More file actions
27 lines (22 loc) · 781 Bytes
/
SparseTable.cpp
File metadata and controls
27 lines (22 loc) · 781 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
#include <bits/stdc++.h>
using namespace std;
template<typename T> struct Sparse {
vector<vector<T>> table;
void build(vector<T> &v){
int N = v.size(), MLOG = 32 - __builtin_clz(N);
table.assign(MLOG, v);
for(int p=1; p < MLOG; p++)
for(int i=0; i + (1 << p) <= N; i++)
table[p][i] = min(table[p-1][i], table[p-1][i+(1<<(p-1))]);
}
T query(int l, int r){
int p = 31 - __builtin_clz(r - l + 1); //floor log
return min(table[p][l], table[p][ r - (1<<p)+1 ]);
}
};
/*LATEX_DESC_BEGIN***************************
**Sparse Table** for Range Minimum Query [L, R] [0, N-1]
build: O(N log N) Query: O(1)
build(v) -> v = Original Array
if you want a static array, do this: for(int i=0; i<N; i++) table[0][i] = v[i];
*****************************LATEX_DESC_END*/