1. 程式人生 > >POJ 3264 Balanced Lineup(線段樹區間查詢)

POJ 3264 Balanced Lineup(線段樹區間查詢)

Balanced Lineup

Description

For the daily milking, Farmer John'sNcows (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 ofQ(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,NandQ.
Lines 2..N+1: Linei
+1 contains a single integer that is the height of cowi
LinesN+2..N+Q+1: Two integersAandB(1 ≤ABN), representing the range of cows fromAtoBinclusive.

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到N編號,對這群牛進行Q次查詢操作,每次查詢返回區間內最高的牛與最矮的牛的高度差。

解題思路:區間查詢的問題,可以用線段樹解決。同時維護區間最大最小值。

程式碼如下:

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

#define MAXN 50005
#define LEFT(X) 2 * (X) + 1
#define RIGHT(X) 2 * (X) + 2

typedef struct {
    int min;
    int max;
} Node;

Node tree[MAXN * 4];

Node merge(Node x, Node y) {
    Node tmp;
    tmp.min = x.min < y.min ? x.min : y.min;
    tmp.max = x.max > y.max ? x.max : y.max;
    return tmp;
}

void build(int treeIndex, int *arr, int lo, int hi) {
    if (lo == hi) {
        tree[treeIndex].min = arr[lo];
        tree[treeIndex].max = arr[lo];
        return;
    }
    int mid = lo + (hi - lo) / 2;
    build(2 * treeIndex + 1, arr, lo, mid);
    build(2 * treeIndex + 2, arr, mid + 1, hi);
    tree[treeIndex] = merge(tree[LEFT(treeIndex)], tree[RIGHT(treeIndex)]);
}

Node query(int treeIndex, int lo, int hi, int i, int j) {
    if (lo > j || hi < i) {
        Node tmp;
        tmp.min = INT_MAX;
        tmp.max = 0;
        return tmp;
    }
    if (i <= lo && hi <= j) return tree[treeIndex];
    int mid = lo + (hi - lo) / 2;
    if (i > mid) return query(RIGHT(treeIndex), mid + 1, hi, i, j);
    else if (j <= mid)return query(LEFT(treeIndex), lo, mid, i, j);

    Node leftQuery = query(LEFT(treeIndex), lo, mid, i, mid);
    Node rightQuery = query(RIGHT(treeIndex), mid + 1, hi, mid + 1, j);
    return merge(leftQuery, rightQuery);
}

int main(void) {
    int N, Q, a, b;
    int arr[MAXN];
    Node ans;
    scanf("%d %d", &N, &Q);
    for (int i = 0; i < N; i++) scanf("%d", &arr[i]);
    build(0, arr, 0, N - 1);
    while (Q--) {
        scanf("%d %d", &a, &b);
        ans = query(0, 0, N - 1, a - 1, b - 1);
        printf("%d\n", ans.max - ans.min);
    }
    return 0;
}