Balanced Lineup

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

 1 #include <stdio.h>
 2 #include <string.h>
 3 #define inf 1000000005
 4 #include <algorithm>
 5 using namespace std;
 6 
 7 int a[50005];
 8 int mmin,mmax;
 9 
10 struct Node
11 {
12     int l,r;
13     int min,max;
14 }node[200100];
15 
16 void build(int root,int l,int r)
17 {
18     node[root].l = l;
19     node[root].r = r;
20     if(node[root].l==node[root].r)
21     {
22         node[root].min=a[l];
23         node[root].max=a[l];
24         return ;
25     }
26     int mid = (l+r)/2;
27     build(root<<1,l,mid);
28     build(root<<1|1,mid+1,r);
29     node[root].min = min(node[root<<1].min,node[root<<1|1].min);
30     node[root].max = max(node[root<<1].max,node[root<<1|1].max);
31 }
32 void query(int root,int l,int r)
33 {
34     if(l<=node[root].l && r>=node[root].r)
35     {
36         mmin = min(mmin,node[root].min);
37         mmax = max(mmax,node[root].max);
38         return;
39     }
40     int mid=(node[root].l+node[root].r)/2;
41 
42     if(r<=mid) query(root<<1,l,r);
43     else if(l>=mid+1) query(root<<1|1,l,r);
44     else
45     {
46         query(root<<1,l,mid);
47         query(root<<1|1,mid+1,r);
48     }
49 }
50 
51 int main()
52 {
53     int n,q,b,c;
54     while(scanf("%d %d",&n,&q)!=EOF)
55     {
56         for(int i=1; i<=n; i++) scanf("%d",&a[i]);
57         build(1,1,n);
58         while(q--)
59         {
60             scanf("%d%d",&b,&c);
61             mmin = inf;
62             mmax =-inf;
63             query(1,b,c);
64             printf("%d\n",mmax-mmin);
65         }
66     }
67 
68     return 0;
69 }
线段树(单点更新)

 

posted @ 2013-07-25 16:26  1002liu  阅读(179)  评论(0编辑  收藏  举报