[POJ] 3264 Balanced Lineup [ST算法]

Balanced Lineup
Time Limit: 5000MS   Memory Limit: 65536K
Total Submissions: 34306   Accepted: 16137
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 will take a contiguous range of cows from the milking lineup to play the game. However, for all the cows to have 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 ≤ 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, N and 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 A and B (1 ≤ A ≤ B ≤ N), representing the range of cows from A to B inclusive.

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 3
1
7
3
4
2
5
1 5
4 6
2 2

Sample Output

6
3
0

Source

 
题解:典型的RMQ问题。Sparse-Table算法的应用。预处理时间复杂度O(nlogn),查询时间复杂度O(1);
 
代码:
 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 long
12 
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 }

 

posted @ 2014-08-13 21:04  SXISZERO  阅读(342)  评论(0编辑  收藏  举报