Balanced Lineup(線段樹求區間最大值)

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

題意:
一串數,求給定區間最大值和最小值之差

思路:
線段樹,都不需要更新的

#include <stdio.h>
#include <stdlib.h>

int a[50005], minx, maxx;
struct node
{
    int left, right, max, min;
}tree[200005];

int min(int x, int y)
{
    if(x>=y) return y;
    else return x;
}

int max(int x, int y)
{
    if(x<=y) return y;
    else return x;
}

void build(int x, int y, int k)
{
    tree[k].left = x;
    tree[k].right = y;
    if(x==y)
    {
        tree[k].min = tree[k].max = a[x];
        return;
    }
    else
    {
        int mid = (x + y) / 2;
        if(y<=mid) build(x, mid, 2*k);
        else if(x>=mid+1) build(mid+1, y, 2*k+1);
        else
        {
            build(x, mid, 2*k);
            build(mid+1, y, 2*k+1);
        }
        tree[k].min = min(tree[2*k].min, tree[2*k+1].min);
        tree[k].max = max(tree[2*k].max, tree[2*k+1].max);
    }
}

void ask(int x, int y, int k)
{
    if(x<=tree[k].left && tree[k].right<=y)
    {
        if(tree[k].min<minx||minx==-1) minx = tree[k].min;
        if(tree[k].max>maxx||maxx==-1) maxx = tree[k].max;
        return;
    }
    else
    {
        int mid = (tree[k].left + tree[k].right) / 2;
        if(y <= mid) ask(x, y, 2*k);
        else if(x>=mid+1) ask(x, y, 2*k+1);
        else
        {
            ask(x, y, 2*k);
            ask(x, y, 2*k+1);
        }
    }
}

int main()
{
    int n, m, i, x, y;
    scanf("%d %d", &n, &m);
    for(i=1;i<=n;i++)
    {
        scanf("%d", &a[i]);
    }
    build(1, n, 1);
    while(m--)
    {
        scanf("%d %d", &x, &y);
        minx = maxx = -1;
        ask(x, y, 1);
        printf("%d\n", maxx - minx);
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章