Skip to content

Instantly share code, notes, and snippets.

@miguelAlessandro
Created June 15, 2017 09:55
Show Gist options
  • Save miguelAlessandro/7d3f60ca83ce8c630e17adbcfaefaa83 to your computer and use it in GitHub Desktop.
Save miguelAlessandro/7d3f60ca83ce8c630e17adbcfaefaa83 to your computer and use it in GitHub Desktop.
//sparse_table
//complexity:
// min_range - O(1)
// build - O(n * log n)
const int N = 100002;
const int LogN = 18;
int st[N][LogN];
int n;
void build(int a[]){
for(int i = 0; i < n; ++i)
st[i][0] = a[i];
for(int k = 1; k < LogN; ++k)
for(int i = 0; i + (1<<k) < n; ++i)
st[i][k] = min(st[i][k-1], st[i+(1<<k-1)][k-1]);
}
int min_range(int l, int r){
int k = 31 - __builtin_clz(r - l + 1);
return min(st[l][k], st[r-(1<<k)+1][k]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment