Click to open link
Balanced Lineup
Time Limit: 5000MS |
|
Memory Limit: 65536K |
Total Submissions: 36215 |
|
Accepted: 16954 |
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
Give the height of the cow ask for the maximum height difference in a range
RMQ Problem First St algorithm: The code is lame.
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #define MAXN 55555using namespace Std;int prelog2[maxn],stmax[maxn][35],stmin[maxn][35];int n,a[maxn];void init () {prelog2[1]=0; for (int i=2;i<=n;i++) {prelog2[i]=prelog2[i-1];if ((1<<prelog2[i]+1) ==i) {prelog2[i]++;}} for (int i=n;i>=1;i--) {stmax[i][0]=stmin[i][0]=a[i];for (int j=1; (i+ (1<<j)-1) <=n;j++) {Stmax[i][j]=max ( stmax[i][j-1],stmax[i+ (1<<j-1)][j-1]) stmin[i][j]=min (stmin[i][j-1],stmin[i+ (1<<j-1)][j-1]);}}} int getmax (int l,int r) {int Len=r-l+1;return max (stmax[l][prelog2[len]],stmax[r-(1<<prelog2[len]) +1][prelog2[ Len]]); int getmin (int l,int r) {int Len=r-l+1;return min (stmin[l][prelog2[len]],stmin[r-(1<<prelog2[len]) +1][prelog2[ Len]]); int main () {int q;scanf ("%d%d", &n,&q), for (int i=1;i<=n;i++) {scanf ("%d", &a[i]);} Init (); while (q--) {int l,r;scanf ("%d%d", &l,&r);p rintf ("%d\n", Getmax (l,r)-getmin (L,r));} return 0;}
POJ 3264 Balanced Lineup St algorithm