ST(Sparse Table)算法学习参考博客:http://blog.csdn.net/niushuai666/article/details/6624672
O(nlogn)预处理,O(1)查询
1 #include<cstdio> 2 #include<algorithm> 3 #include<cmath> 4 using namespace std; 5 const int N = 10001; 6 int ma[N][20]; 7 int a[N]; 8 int n; 9 void RMQ_init(){ 10 int i, j; 11 for(i = 0; i < n; ++i) ma[i][0] = a[i]; 12 int m = (int)(log(n*1.0) / log(2.0)); 13 for(i = 1; i <= m; ++i){ 14 for(j = 0; j < n; ++j){ 15 ma[j][i] = ma[j][i-1]; 16 if(j + (1 << (i-1)) <= n) 17 ma[j][i] = max(ma[j][i], ma[j + (1 << (i-1))][i-1]); 18 } 19 } 20 } 21 int RMQ_max(int l, int r){ 22 int m = (int)(log((r-l+1)*1.0) / log(2.0)); 23 return max(ma[l][m], ma[r - (1 << m) + 1][m]); 24 } 25 int main(){ 26 int q, i; 27 scanf("%d", &n); 28 for(i = 0; i < n; ++i) scanf("%d", &a[i]); 29 RMQ_init(); 30 scanf("%d", &q); 31 int l, r; 32 while(q--){ 33 scanf("%d%d", &l, &r); 34 printf("%d ", RMQ_max(l, r)); 35 } 36 return 0; 37 }