Last active
August 29, 2015 14:23
-
-
Save yinyanghu/03a84d343a34637f3f2d to your computer and use it in GitHub Desktop.
RMQ - Sparse Table Algorithm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define MAXST 100000 | |
#define LogMAXST 18 | |
inline int clz(int x){return __builtin_clz(x);} | |
inline int lg2(int x){return !x ? -1 : 31 - clz(x);} | |
struct SparseTable { | |
int N; | |
int F[LogMAXST][MAXST]; | |
SparseTable() {} | |
SparseTable(int n, int *A) { | |
N = n; | |
for (int i = 0; i < n; ++ i) | |
F[0][i] = A[i]; | |
for (int k = 1; (1 << k) <= n; ++ k) | |
for (int i = 0; i + (1 << k) - 1 < n; ++ i) | |
F[k][i] = min(F[k - 1][i], F[k - 1][i + (1 << (k - 1))]); | |
} | |
// must be x <= y | |
int Query(int x, int y) { | |
if (x == y) return F[0][x]; | |
k = lg2(y - x + 1); | |
return min(F[k][x], F[k][y - (1 << k) + 1]); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment