Range Minimum value problem (range Minimum QUERY,RMQ)

Source: Internet
Author: User

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&LT;&LT;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&LT;&LT;J) +1;printf("%d\n", Min (Calc[l][j], calc[rr][j])); }return 0;}

Range Minimum value problem (range Minimum QUERY,RMQ)

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.