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 ≤ 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

题意:给出一串的数字,然后给出一个区间a b,输出从a到b的最大的数和最小的数的差。线段树简单题,不需要更新区间。

#include
#include
#include
#define INF 0x3f3f3f3f
#define N  51000
int nmin,nmax;
struct node
{
    int l,r;
    int nmin,nmax;
}tree[4*N];
int max(int a,int b)
{
   return a > b ? a : b;
}
int min(int a,int b)
{
    return a < b ? a : b;
}
void build(int i,int l,int r)
{
    tree[i].l = l;
    tree[i].r = r;
    if(l == r)
    {
        scanf("%d",&tree[i].nmin);
        tree[i].nmax = tree[i].nmin;
        return ;
    }
    int mid = (l + r)/2;
    build(2*i,l,mid);
    build(2*i+1,mid+1,r);
    tree[i].nmax = max(tree[i*2].nmax, tree[i*2+1].nmax);
    tree[i].nmin = min(tree[i*2].nmin, tree[i*2+1].nmin);
}
void Find(int i,int l,int r)
{
    if(tree[i].nmax <= nmax&& tree[i].nmin >= nmin)
    return ;
    if(tree[i].l == l&&tree[i].r == r)
    {
        nmin = min(tree[i].nmin,nmin);
        nmax = max(tree[i].nmax,nmax);
        return ;
    }
    int mid = (tree[i].l + tree[i].r)/2;
    if(r <= mid)
    Find(2*i,l,r);
    else if(l>mid)
    Find(2*i+1,l,r);
    else
    {
        Find(2*i,l,mid);
        Find(2*i+1,mid+1,r);
    }
}
int main()
{
     int n,t,a,b;
     while(~scanf("%d %d",&n,&t))
     {
         build(1,1,n);
         while(t--)
         {
            scanf("%d %d",&a,&b);
            nmax = -INF;
            nmin = INF;
            Find(1,a,b);
            printf("%d\n",nmax - nmin);
         }
     }
     return 0;
}

你可能感兴趣的:(线段树)