Balanced Lineup
Time Limit: 5000MS |
|
Memory Limit: 65536K |
Total Submissions: 39046 |
|
Accepted: 18291 |
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
Source
Usaco January Silver
AC Code
#include <stdio.h> #include <string.h> #include <math.h> #define MAX (b) (a>b?a:b) #define MIN (A, b ) (a>b?b:a) int minv[50050][20],maxv[50050][20];int a[50050];void init (int n) {int i,j,k;for (i=1;i<=n;i++) {maxv[ I][0]=minv[i][0]=a[i];} For (J=1, (1<<j) <=n;j++) {for (k=1;k+ (1<<j) -1<=n;k++) {minv[k][j]=min (minv[k][j-1],minv[k+ (1< < (j-1)][j-1]) Maxv[k][j]=max (maxv[k][j-1],maxv[k+ (1<< (j-1))][j-1]);}}} int Q_max (int l,int r) {int k= (int) (log (double) (r-l+1)/(log (2.0))); return Max (maxv[l][k],maxv[r-(1<<k) +1][k] );} int q_min (int l,int r) {int k= (int) (log (double) (r-l+1)/(log (2.0))); return min (minv[l][k],minv[r-(1<<k) +1][k] );} int main () {int n,m;while (scanf ("%d%d", &n,&m)!=eof) {int i;for (i=1;i<=n;i++) {scanf ("%d", &a[i]);} Init (n), while (m--) {int l,r;scanf ("%d%d", &l,&r);p rintf ("%d\n", Q_max (l,r)-q_min (L,r));}}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
POJ Topic 3264 Balanced Lineup (RMQ)