RMQ: (interval max problem)
Essentially dynamic programming, with D (I, j) representing the minimum value of a section of an element that starts with a length of 2^j from I, you can use a recursive method to calculate D (i, J): D (i, j) = min{D (i, j-1), D (i + 2^ (j-1), j-1)}
Because 2^j <= n so the number of elements in the D array does not exceed Nlogn, the total time complexity is O (NLOGN);
#include <iostream> #include <cstring> #include <cstdlib> #include <cstdio> #include < algorithm> #include <vector> #include <set> #include <map> #include <queue> #include < cmath> #include <stack> #define LL long longusing namespace Std;const int maxn = 50000 + 10;int D[maxn][20];int a[m Axn];int N, q;void rmq_init_min () {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_min (int L, int R) {int k = 0; while ((1<< (k+1)) <= r-l + 1) k++; return min (D[l][k], d[r-(1<<k) +1][k]);} int dp[maxn][20];void Rmq_init_max () {for (int i=0;i<n;i++) dp[i][0] = A[i]; for (int j=1, (1<<j) <= n;j++) for (int i=0;i+ (1<<J)-1 < n;i++) Dp[i][j] = max (dp[i][j-1) , dp[i+ (1<< (j-1))][j-1]);} int Rmq_max (int L, int R) {int k = 0; While(1<< (k+1)) <= r-l + 1) k++; Return Max (Dp[l][k], dp[r-(1<<k) +1][k]);} int main () {while (scanf ("%d%d", &n, &q)!=eof) {for (int i=0;i<n;i++) scanf ("%d", &a [i]); Rmq_init_min (); Rmq_init_max (); int L, R; while (q--) {scanf ("%d%d", &l, &r); int L = rmq_min (L-1, R-1); int r = Rmq_max (L-1, R-1); printf ("%d\n", r-l); }} return 0;}
POJ 3264 Balanced Lineup (RMQ detailed)