Balanced Lineup POJ - 3264

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 ≤ ABN), 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

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<iostream>
 4 #include<algorithm>
 5 #define INF 1e8
 6 #define lson l , m , rt << 1
 7 #define rson m+1,r,  rt << 1 | 1
 8 using namespace std;
 9 
10 const int maxn=55000;
11 
12 int n,q;
13 int mi[maxn<<2],ma[maxn<<2];
14 
15 void Pushup(int rt){
16     mi[rt]=min(mi[rt<<1],mi[(rt<<1)|1]);
17     ma[rt]=max(ma[rt<<1],ma[(rt<<1)|1]);
18 } 
19 
20 void Build(int l,int r,int rt){
21     if(l==r){
22         scanf("%d",&mi[rt]);
23         ma[rt]=mi[rt];
24         return;
25     }
26     int m=(l+r)>>1;
27     Build(lson);
28     Build(rson); 
29     Pushup(rt);
30 } 
31 
32 int Query_min(int L,int R,int l,int r,int rt){
33     if(L<=l&&r<=R) return mi[rt];
34     int m=(l+r)>>1;
35     int temp_min=INF;
36     if(L<=m) temp_min=min(temp_min,Query_min(L,R,lson));
37     if(R>m)  temp_min=min(temp_min,Query_min(L,R,rson));
38     return temp_min;
39 }
40 
41 int Query_max(int L,int R,int l,int r,int rt){
42     if(L<=l&&r<=R) return ma[rt];
43     int m=(l+r)>>1;
44     int temp_max=0;
45     if(L<=m) temp_max=max(temp_max,Query_max(L,R,lson));
46     if(R>m)  temp_max=max(temp_max,Query_max(L,R,rson));
47     return temp_max;
48 }
49 
50 int main()
51 {   cin>>n>>q;
52     Build(1,n,1);
53     while(q--){
54         int a,b;
55         scanf("%d%d",&a,&b);
56         int ans=Query_max(a,b,1,n,1)-Query_min(a,b,1,n,1);
57         cout<<ans<<endl;
58     }
59     return 0;
60 }

 

posted @ 2017-08-15 14:24  天之道,利而不害  阅读(225)  评论(0编辑  收藏  举报