对于一个数组a[1],a[2],a[3]......构建一个Sparse Table表
i | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
a | 5 | 3 | 7 | 9 | 6 | 4 | 1 | 2 |
t0 | 5 | 3 | 7 | 9 | 6 | 4 | 1 | 2 |
t1 | 3 | 3 | 7 | 6 | 4 | 1 | 1 | |
t2 | 3 | 3 | 4 | 1 | 1 | |||
t3 | 1 |
其中ti,j表示的是aj,aj+1,,......aj+2^i 的最小值,首先求出满足2^i<=y-x<2^(i+1),然后min(t_(i,x),t_(i,y-2^i+1))就是ax到ay区间的最小值.......i=(int)(log(y-x+1)/log2);
void Init(){
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) <= 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) <= r-l+1)k++;
k--;
return min(d[l][k], d[r-(1<<k)+1][k]);
}
预处理思想,复杂度o(nlogn),查询复杂度o(1)