Title Link: http://poj.org/problem?id=3264
Balanced Lineup
Time Limit: 5000MS |
|
Memory Limit: 65536K |
Total Submissions: 47515 |
|
Accepted: 22314 |
Case Time Limit: 2000MS |
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
Topic : Given an array, and then give an interval [a, a], the output from A to b the difference between the maximum and minimum values.
RMQ and line segment trees are available
RMQ Code:
1#include <stdio.h>2 #defineMAX (A, B) (A>b a:b)3 #defineMIN (A, B) (A>b b:a)4 #defineN 500105 inta[n],ma[n][ -],mi[n][ -];6 7 voidST (intN)8 {9 inti,j;Ten for(i=1; i<=n;i++) Onemi[i][0]=ma[i][0]=A[i]; A - for(j =1; (1<<J) <= N; J + +) - for(i =1; i + (1<<J)-1<= N; i + +) the { -Ma[i][j]=max (ma[i][j-1],ma[i+ (1<< (J-1))][j-1]); -Mi[i][j]=min (mi[i][j-1],mi[i+ (1<< (J-1))][j-1]); - } + } - + intRmqintAintb) A { at intK =0; - while((1<< (k +1)) <= b-a+1) k++; - returnMAX (ma[a][k],ma[b-(1<<K) +1][k])-min (mi[a][k],mi[b-(1<<K) +1][k]); - } - - intMain () in { - intn,i,q,x,y; to while(SCANF ("%d%d", &n,&q)!=-1) + { - for(i=1; i<=n;i++) thescanf"%d", A +i); * ST (n); $ for(i=1; i<=q;i++)Panax Notoginseng { -scanf"%d%d",&x,&y); theprintf"%d\n", RMQ (x, y)); + } A } the return 0; +}
View Code
POJ 3264 interval Maximum minimum value sparse_table algorithm