// concept 3264
//O(n log(n) )
// can only be used for static data and are only seeking the maximum or minimum interval
. 1 #include <cstdio> 2 #include <the cmath> . 3 #include <the iostream> . 4 #include <algorithm> . 5 the using namespace STD; . 6 . 7 const int MAXN = 5E4 + . 5 ; . 8 . 9 int n, m; // number n m queries 10 int a [MAXN]; . 11 int MAXN [MAXN] [ 32 ]; // F [i] [J] represents the number 2 ^ j starting from the maximum value of i-th digit interval [i, i + (<<. 1 J) -1] 12 is int Minn [MAXN] [ 32 ]; 13 is 14 void ST () { 15 for(int i = 1; i <= n; ++i) maxn[i][0] = minn[i][0] = a[i]; 16 int m = (int)log2(n*1.0)/log2(2*1.0); 17 for(int j = 1; j <= m; ++j) { 18 for(int i = 1; i+(1<<j)-1 <= n; ++i) { 19 maxn[i][j] = max(maxn[i][j-1], maxn[i+(1<< (J- 1 ))] [J- 1 ]); 20 by [i] [j] = min (a [i] [J- 1 ], a [i + ( 1 << (J- 1 ))] [J- 1 ]); 21 } 22 } 23 } 24 25 you query ( you have to, you r) { 26 you k = log 2 (r-l + 1 ) / log 2 ( 2 ); 27 return max (maxn [i] [k], maxn [R- ( 1 << k) + 1 ] [a]) - who (by [] [k], from [R- ( 1 << k) + 1][k]); 28 } 29 30 int main() { 31 scanf("%d%d", &n, &m); 32 for(int i = 1; i <= n; ++i) { 33 scanf("%d", &a[i]); 34 } 35 ST(); 36 int l, r; 37 for(int i = 0; i != m; ++i) { 38 scanf("%d%d", &l, &r); 39 printf("%d\n", query(l, r)); 40 } 41 return 0; 42 }
Detailed // See https://blog.csdn.net/a_bright_ch/article/details/81062039