#include <iostream> #include <cmath> #include <algorithm>using namespace std; #define M 100010#define MAXN 500#define MAXM 500int dp[m][18];/** One-dimensional RMQ St algorithm * Constructs RMQ array makermq (int n,int b[]) O (Nlog (n)) algorithm complexity *dp[i][j] means from I to i+2^j- The smallest value in 1 (starting from I 2^j number) *dp[i][j]=min{dp[i][j-1],dp[i+2^ (j-1)][j-1]}* query rmq rmq (int s,int v) * Divide s-v into two 2^k intervals * i.e. k= (int) LOG2 (s-v+1) * Query result should be min (Dp[s][k],dp[v-2^k+1][k]) */void makermq (int n,int b[]) {int i,j; for (i=0;i<n;i++) dp[i][0]=b[i]; For (J=1, (1<<j) <=n;j++) for (i=0;i+ (1<<j) -1<n;i++) dp[i][j]=min (dp[i][j-1],dp[i+ (1<&L t; (j-1))][j-1]);} int rmq (int s,int v) {int k= (int) (log (v-s+1) *1.0)/log (2.0)); return min (dp[s][k],dp[v-(1<<k) +1][k]);} void Makermqindex (int n,int b[])//returns the lowest value corresponding to the subscript {int i,j; for (i=0;i<n;i++) dp[i][0]=i; For (J=1, (1<<j) <=n;j++) for (i=0;i+ (1<<j) -1<n;i++) dp[i][j]=b[dp[i][j-1]] < b[dp[i+ (1 << (j-1)][j-1]]? DP[I][J-1]:d p[i+ (1<< (j-1))][j-1];} int rmqindex (int s,int v,int b[]) {int k= (int) (log (v-s+1) *1.0)/log (2.0)); Return b[dp[s][k]]<b[dp[v-(1<<k) +1][k]]? Dp[s][k]:d p[v-(1<<k) +1][k];} int main () {int a[]={3,4,5,7,8,9,0,3,4,5}; Returns subscript Makermqindex (sizeof (a)/sizeof (A[0]), a); Cout<<rmqindex (0,9,a) <<endl; Cout<<rmqindex (4,9,a) <<endl; Returns the minimum value MAKERMQ (sizeof (a)/sizeof (A[0]), a); COUT<<RMQ (0,9) <<endl; COUT<<RMQ (4,9) <<endl; return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
RMQ (St online algorithm template)