Rmq (range minimum/maximum query) is the problem of finding the maximum value of a range.
For array a with a length of N, perform several queries. For the range [L, R], return the minimum (large) value of the subscript in array a in [L, R.
We can use the line segment tree to solve this problem. The complexity of preprocessing is O (nlogn), and the complexity of query is O (logn ).
A better solution is the st algorithm. The sparse_table algorithm is a sparse table algorithm. This method can be used to query O (1) After O (nlogn) preprocessing.
This algorithm is very easy to implement.
Define f [I, K] to indicate the minimum value of the element in the interval of 2 ^ K starting from I.
When K = 0, the value of F [I, 0] is obviously the value of a [I.
When K> 0, for the range of the length starting from I to 2 ^ K, its minimum value is obviously the length starting from I to 2 ^ (k-1) the minimum value in the interval is smaller than the minimum value in the interval from I + 2 ^ (k-1) to 2 ^ (k-1.
There is a recursive formula F [I, K] = min {f [I, k-1], F [I + 2 ^ (k-1), k-1]}
Because 2 ^ k <= N, the number of elements in the f array does not exceed nlogn, and each element can be calculated within the time of O (1, therefore, the total time is O (nlogn ).
1 int f [maxn] [20]; 2 // The element numbers from 1 to N3 void rmq_init (int A [], int N) {4 for (INT I = 1; I <= N; I ++) f [I] [0] = A [I]; 5 for (int K = 1; (1 <k) <= N; k ++) 6 for (INT I = 1; I + (1 <k)-1 <= N; I ++) 7 f [I] [k] = min (F [I] [k-1], F [I + (1 <(k-1)] [k-1]); 8}
Rmq preprocessing
For query operations [L, R], define K as the maximum integer that satisfies 2 ^ k <= R-L + 1.
Then the interval starting with L is 2 ^ K and the interval ending with R is 2 ^ K, which can completely cover [L, R].
Therefore, the smaller of the minimum values of these two ranges is the minimum value of the queried range [L, R.
1 int RMQ(int L,int R){2 int k=0;3 while ((1<<(k+1))<=R-L+1) k++;4 return min(d[L][k],d[R-(1<<k)+1][k]);5 }
Rmq Query
The St algorithm can also find the subscript of the most value, as long as the stored value in the f array is changed to the subscript of array.