POJ 3264 Balanced Lineup(线段树区间查询)

来源:互联网 发布:席德梅尔 知乎 编辑:程序博客网 时间:2024/05/19 20:49

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 31734251 54 62 2

Sample Output

630

题目大意:有一群高矮不同的牛排成一队并按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) + 2typedef 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;}