RMQ problem: Given an interval of length n, M asks for the maximum/minimum value of each interval element of Li to Ri.
RMQ's high-level writing generally has two kinds, namely the line segment tree and the St table.
This article mainly explains the St table's writing. (Take the interval maximum as an example)
St table: A multiplication algorithm using DP to solve interval maximum value.
Definition: F[i][j] represents the maximum value of the interval between I and i+2^j-1.
Pretreatment: F[i][0]=a[i]. The maximum value of the interval I to I is a[i].
State transfer: Divide f[i][j] Evenly into two segments, one for F[i][j-1] and the other for f[i+2^ (j-1)][j-1].
The lengths of both segments are 2^j-1. The maximum value of f[i][j] is the maximum value in the maximum of the two paragraphs.
Get F[i][j]=max (f[i][j-1],f[i+2^ (j-1)][j-1]).
voidRMQ (intN) { /*Note that the outer loop starts with J because the initial state is f[i][0], and I is the outer layer where some states do not traverse. */ for(intj=1; j<= -; j + +) for(intI=1; i<=n;i++) if(I+ (1<<J)-1<=N) F[i][j]=max (f[i][j-1],f[i+ (1<< (J-1))][j-1]);}
Query: Need to query the interval is [i,j], you need to find two to cover the closed interval of the smallest power interval.
These two intervals can be repeated, since the intersection of two intervals has no effect on the interval's maximum value. such as
Of course, the interval and must not be. This is the restriction of RMQ.
Since the length of the interval is j-i+1, k=log2 (j-i+1) can be taken.
Then RMQ (a,i,j) =max (F[i][k],f[j-2^k+1][k]).
Code:
#include <algorithm>#include<iostream>#include<cstring>#include<cstdio>#include<cmath>using namespacestd;inta[100001],f[100001][ -];inlineintRead () {intx=0, f=1; CharC=GetChar (); for(;! IsDigit (c); c=GetChar ())if(c=='-') F=-1; for(; IsDigit (c); c=GetChar ()) x=x*Ten+c-'0'; returnx*F;}voidRMQ (intN) { for(intj=1; j<= -; j + +) for(intI=1; i<=n;i++) if(I+ (1<<J)-1<=N) F[i][j]=max (f[i][j-1],f[i+ (1<< (J-1))][j-1]); }intMain () {intN=read (), m=read (); for(intI=1; i<=n;i++) a[i]=read (); for(intI=1; i<=n;i++) f[i][0]=A[i]; RMQ (N); while(m--){ intI=read (), j=read (); intI=jint) (Log (Double) (j-i+1))/log (2.0)); printf ("%d\n", Max (f[i][k],f[j-(1<<K) +1][k])); } return 0;}
ST Table algorithm of "multiplication" rmq