POJ 3264 Balanced Lineup

Balanced Lineup

Time Limit: 5000MS Memory Limit: 65536K
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

思路:

线段树的一题,首先就是建树,然后再建树的时候不断更新区间的最大值以及最小值,最后在查询的时候就可以直接找到这个区间并且用里面的最大值和最小值就行了。

#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;
const int maxn = 50010;
const int inf = 0x7fffffff;
struct NODE {
    int l;
    int r;
    int high;
    int MAX;
    int MIN;
    int mid() {
        return (l + r) >> 1;
    }
};
NODE node[maxn << 2];
void PushUp(int rt) {
    node[rt].MAX = max(node[rt << 1].MAX, node[rt << 1 | 1].MAX);
    node[rt].MIN = min(node[rt << 1].MIN, node[rt << 1 | 1].MIN);
}
void BuildTree(int l, int r, int rt) {
    node[rt].l = l;
    node[rt].r = r;
    if (l == r) {
        scanf("%d", &node[rt].high);
        node[rt].MAX = node[rt].MIN = node[rt].high;
        return ;
    }
    int m = node[rt].mid();
    BuildTree(l, m, rt << 1);
    BuildTree(m + 1, r, rt << 1 | 1);
    PushUp(rt);
}
int Max = 0, Min = inf;
void Query(int l, int r, int rt) {
    if (node[rt].l == l && node[rt].r == r) {
        Max = max(Max, node[rt].MAX);
        Min = min(Min, node[rt].MIN);
        return ;
    }
    int m = node[rt].mid();
    if (r <= m) Query(l, r, rt << 1);
    else if (l > m) Query(l, r, rt << 1 | 1);
    else {
        Query(l, m, rt << 1);
        Query(m + 1, r, rt << 1 | 1);
    }
}
int main() {
    int n, m;
    scanf("%d %d", &n, &m);
    BuildTree(1, n, 1);
    while (m--) {
        int a, b;
        Max = 0;
        Min = inf;
        scanf("%d %d", &a, &b);
        Query(a, b, 1);
        printf("%d\n", Max - Min);
    }
    return 0;
}

全部评论

相关推荐

05-10 16:48
门头沟学院 Java
程序员小白条:主要原因,投递太晚了,快手应该早点溜了,你都从去年9月开始的,半年也差不多3月跑路了,这样的话,至少有5个以上的面试机会
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务