RMQ (St online algorithm template)

Source: Internet
Author: User

#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&LT;&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&LT;&LT;RMQ (0,9) <<endl;    COUT&LT;&LT;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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.