[线段树 单点更新 区间查询多个值] G - Balanced Lineup POJ - 3264

Balanced Lineup
Time Limit: 5000MS   Memory Limit: 65536K
Total Submissions: 61985   Accepted: 28950
Case Time Limit: 2000MS

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



#include <iostream>
#include <cstdio>
using namespace std;

const int mn = 50010;
const int mq = 200010;
const int inf = 0x7fffffff;

struct node
{
    int l, r, minn, maxx;
} t[4 * mn];

void build(int i, int l, int r)
{
    t[i].l = l, t[i].r = r;
    if (l == r)
    {
        int a;
        scanf("%d", &a);
        t[i].maxx = t[i].minn = a;
        return;
    }
    int m = (l + r) / 2;
    build(2 * i, l, m);
    build(2 * i + 1, m + 1, r);
    t[i].minn = min(t[2 * i].minn, t[2 * i + 1].minn);
    t[i].maxx = max(t[2 * i].maxx, t[2 * i + 1].maxx);
    return;
}

int x, y = inf;     /// 全局变量记录区间最值
void query(int i, int a, int b)
{
    int l = t[i].l, r = t[i].r;
    if (a == l && r == b)
    {
        x = max(x, t[i].maxx);  /// 区间包含 更新最值
        y = min(y, t[i].minn);
        return;
    }
    
    int m = (l + r) / 2;
    if (b <= m)
        query(2 * i, a, b);
    else if (a > m)
        query(2 * i + 1, a, b);
    else    /// 分别查询并更新
    {
        query(2 * i, a, m);
        query(2 * i + 1, m + 1, b);
    }
    return;
}
int main()
{
    int n, q;
    scanf("%d %d", &n, &q);
    build(1, 1, n);
    while (q--)
    {
        int a, b;
        scanf("%d %d", &a, &b);
        
        x = 0, y = inf;     /// 初始化
        query(1, a, b);
        printf("%d\n", x - y);
    }
    return 0;
}


猜你喜欢

转载自blog.csdn.net/ummmmm/article/details/81043959