Problem description
Given a sequence of n elements {A1,a2,......,an}, find the minimum value within the required interval query (L,R): Min{al,al+1,......, AR}. Hiho16
Algorithm description
The most commonly used Tarjan sparse-table algorithm is described here, its preprocessing time complexity is O (Nlogn), and the query time only needs O (1). If Calc (i,j) represents the minimum value of a sub-sequence that starts with a length of 2j, it is calculated using a cyclic method: calc[i][j] = min (calc[i][j-1],calc[i+2j-1)][j-1]), the code is as follows:
void RMQ_init ( Span class= "Hljs-keyword" >void ) {int index = Floor (log (n)/log (2 )"); for (int j = 1 ; J <= Index; j + +) {for (int i = 1; i+ (1 <<j)-1 <=n; i++) {Calc[i][j] = min (Calc[i][j-1 ],calc[i+ (1 << (j-1 )] [J-1 ]); } }}
Note: Here the sequence starts at index 1.
After the preprocessing is complete, how to use this information, for a query [L,r], as long as the number is less than this interval length of the largest 2 non-negative integer power exponent--j, then the minimum value in this interval is min{calc[l][j], Calc[r-2j+1][j]}, The entire [l,r] interval can be covered by these two intervals, and the minimum value is not affected even if there is a intersection between the ends.
Code
#include <cstdio>#include <algorithm>#include <math.h>#define SIZE 1000005using namespace STD;intArr[size];intcalc[size][ -];intN, Q;voidRmq_init (void){intindex = Floor(Log(n)/Log(2)); for(intj =1; J <= Index; J + +) { for(inti =1; i+ (1<<J)-1<=n; i++) {Calc[i][j] = min (calc[i][j-1],calc[i+ (1<< (J-1))][j-1]); } }}intMainvoid) {scanf("%d", &n); for(inti =1; I <= N; i++) {scanf("%d", arr + i); calc[i][0] = Arr[i]; } rmq_init ();scanf("%d", &q);intL, R; for(inti =0; i < Q; i++) {scanf("%d%d", &l, &r);intj = Floor(Log(R-l +1) /Log(2));intrr = R-(1<<J) +1;printf("%d\n", Min (Calc[l][j], calc[rr][j])); }return 0;}
Range Minimum value problem (range Minimum QUERY,RMQ)