Balanced lineup
Time limit:5000 Ms |
|
Memory limit:65536 K |
Total submissions:34306 |
|
Accepted:16137 |
Case time limit:2000 ms |
Description
For the daily milking, Farmer John'sNCows (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 will take a contiguous range of cows from the milking lineup to play the game. however, for all the cows to have fun they shocould not differ too much in height.
Farmer John has made a listQ(1 ≤Q≤ 200,000) potential groups of cows and Their heights (1 ≤Height≤ 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 group.
Input
Line 1: two space-separated integers,
NAnd
Q.
Lines 2 ..
N+ 1: Line
I+ 1 contains a single integer that 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
BIntrusive.
Output
Lines 1 ..
Q: Each line contains a single integer that is a response to a reply and indicates the difference in height between the tallest and shortest cow in the range.
Sample Input
6 31734251 54 62 2
Sample output
630
Source
Usaco 2007 January silver
Question: Typical rmq problems. Sparse-table algorithm. Preprocessing time complexity O (nlogn) and query time complexity O (1 );
Code:
1 #include<stdio.h> 2 #include<string.h> 3 #include<math.h> 4 #include<ctype.h> 5 #include<stdlib.h> 6 #include<stdbool.h> 7 8 #define rep(i,a,b) for(i=(a);i<=(b);i++) 9 #define clr(x,y) memset(x,y,sizeof(x))10 #define sqr(x) (x*x)11 #define LL long long12 13 int i,j,n,m,x,y,q,maxn,minn,14 d[51000][50],f[51000][50];15 16 int min(int a,int b)17 {18 if(a<b) return a;19 return b;20 }21 22 int max(int a, int b)23 {24 if(a>b) return a;25 return b;26 }27 28 int RMQ_init()29 {30 int i;31 32 for(j=1;(1<<j)<=n;j++)33 for(i=1;i+(1<<j)-1<=n;i++) {34 d[i][j]=min(d[i][j-1],d[i+(1<<(j-1))][j-1]);35 f[i][j]=max(f[i][j-1],f[i+(1<<(j-1))][j-1]);36 }37 }38 39 int RMQ(int L,int R)40 {41 int k=0;42 43 while(1<<(k+1)<=R-L+1) k++;44 minn=min(d[L][k],d[R-(1<<k)+1][k]);45 maxn=max(f[L][k],f[R-(1<<k)+1][k]);46 }47 48 int main()49 {50 int i;51 52 clr(d,3); 53 clr(f,-1); 54 scanf("%d%d",&n,&q);55 rep(i,1,n) {56 scanf("%d",&d[i][0]);57 f[i][0]=d[i][0];58 }59 60 RMQ_init();61 62 while(q--) {63 scanf("%d%d",&x,&y);64 RMQ(x,y);65 printf("%d\n",maxn-minn);66 }67 68 return 0;69 }