对于长度为n的数列A,回答若干询问RMQ(A,i,j)(i,j<=n),返回数列A中下标在i,j里的最小(大)值。
void RMQ_init(const vector<int>& A) {
int n = A.size();
for(int i = 0; i < n; i++) d[i][0] = A[i];
for(int j = 1; (1<<j) <= n; j++) {
for(int i = 0; i + (1<<j) - 1 < n; i++) {
d[i][j] = min(d[i][j-1], d[i + (1<<(j-1))][j-1]);
}
}
}
int RMQ(int L, int R) {
int k = 0;
while((1<<(k+1)) <= R-L+1) k++; //如果2^k+1 <= R-L+1,那么k还可以加1
return min(d[L][k], d[R-(1<<k)+1][k]);
}