forked from nikhilgarg28/libalgo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRMQ.cpp
More file actions
38 lines (33 loc) · 675 Bytes
/
RMQ.cpp
File metadata and controls
38 lines (33 loc) · 675 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
31
32
33
34
35
36
37
38
const int LOGN = 20;
const int N = 1000005;
int rmq[18][N];
int K[N];
void calcRMQ(const VI & arr)
{
int n=arr.size();
for(int i = 0; i < n; i++)
rmq[0][i] = arr[i];
for(int stp = 1, len = 2; stp < 18; stp++, len<<=1)
for(int i = 0; i < n; i++)
{
int f = i + (len>>1);
if(f < n) rmq[stp][i] = min(rmq[stp-1][i], rmq[stp-1][f]);
else rmq[stp][i] = rmq[stp-1][i];
}
}
}
int getRMQ(int a,int b) // a inclusive, b exclusive
{
if(a==b) return +INF;
int k = K[b-a];
return min(rmq[k][a], rmq[k][b-(1<<k)]);
}
void preprocess()
{
K[0]=-1;
for(int i=1;i<=N;i++)
{
K[i]=K[i-1];
if((i&(i-1))==0) K[i]++;
}
}