Description
For the daily milking, Farmer John's n cows (1≤ n ≤50,000) always line up in the same order. One day Farmer John decides to organize a game of Ultimate frisbee with some of the cows. To keep things simple, he'll take a contiguous range of cows from the milking lineup to play the game. However, for all the cows to has fun they should not differ too much in height.
Farmer John has made a list of Q (1≤ q ≤200,000) Potential groups of cows and their heights (1≤ H Eight ≤1,000,000). For each group, he wants your help to determine the difference in height between the shortest and the tallest cow in the G Roup.
Input
Line 1:two space-separated integers,
Nand
Q.
Lines 2..
N+1:line
I+1 contains a single integer which is the height of cow
I
Lines
N+2..
N+
Q+1:two integers
Aand
B(1≤
A≤
B≤
N), representing the range of cows from
ATo
BInclusive.
Output
Lines 1..
Q: Each line contains a single integer so is a response to a reply and indicates the difference in height between the Tal Lest and shortest cow in the range.
Sample Input
6 31734251 54) 62 2
Sample Output
630
Test instructions: give you a sequence that keeps asking you the difference between the maximum and minimum values of the interval "L,r".
Idea: Because the data is particularly large, so the violent words will definitely time out. So considering the use of RMQ, after a simple study can put this topic to a.
RMQ Blog:http://blog.csdn.net/liang5630/article/details/7917702
AC Code:
1#include <iostream>2#include <cstdio>3 using namespacestd;4 inta[200005],b[200005][ +],c[200005][ +];5 intMain ()6 {7 intN,m,l,r;8 while(~SCANF ("%d%d",&n,&m))9 {Ten for(intI=1; i<=n; i++) One { Ascanf"%d",&a[i]); -b[i][0]=c[i][0]=A[i]; - } the for(intj=1; (1<<J) <=n; J + +) - for(intI=1; i+ (1<< (J-1)) <=n; i++) - { -B[i][j]=max (b[i][j-1],b[i+ (1<< (J-1))][j-1]); +C[i][j]=min (c[i][j-1],c[i+ (1<< (J-1))][j-1]); - //printf ("%d%d%d\n", i,j,b[i][j],c[i][j]); + } A for(intI=0; i<m; i++) at { -scanf"%d%d",&l,&R); - intk=0; - while((1<<K) <=r-l+1) -k++; -printf"%d\n", Max (b[l][k-1],b[r-(1<< (K-1))+1][k-1])-min (c[l][k-1],c[r-(1<< (K-1))+1][k-1])); in } - } to return 0; +}
View Code
poj--3264 Balanced lineup (bare RMQ)