您的位置:首页 > 其它

poj 3264 Balanced Lineup 线段树

2017-10-17 17:56 477 查看
[align=center]Balanced Lineup[/align]

Time Limit: 5000MS Memory Limit: 65536K
Total Submissions: 57383 Accepted: 26886
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 <cstdio>
#include <algorithm>
#define lson l , m , rt << 1
#define rson m + 1 , r , rt << 1 | 1

const int N = 50005;

int Max[N << 2] , Min[N << 2];

void Pushup(int rt)
{
Max[rt] = std::max(Max[rt << 1] , Max[rt << 1 | 1]);
Min[rt] = std::min(Min[rt << 1] , Min[rt << 1 | 1]);
}

void Build(int l , int r , int rt)
{
if(l == r) {
scanf("%d",&Max[rt]);
Min[rt] = Max[rt];
return ;
}
int m = (l + r) >> 1;
Build(lson);
Build(rson);
Pushup(rt);
}

int Query_Max(int L , int R , int l , int r , int rt)
{
if(L <= l && r <= R) {
return Max[rt];
}
int m = (l + r) >> 1;
int res = -1;
if(L <= m) res = std::max(res , Query_Max(L , R , lson));
if(R > m) res = std::max(res , Query_Max(L , R , rson));
return res;
}

int Qmin(int L , int R , int l , int r , int rt)
{
if(L <= l && r <= R) {
return Min[rt];
}
int m = (l + r) >> 1;
int res = 0x7fffffff;
if(L <= m) res = std::min(res , Qmin(L , R, lson));
if(R > m) res = std::min(res , Qmin(L , R , rson));
return res;
}

int main()
{
int n , m;
scanf("%d%d",&n,&m);
Build(1 , n , 1);
for (int i = 0; i < m; i ++) {
int _ , __;
scanf("%d%d",&_,&__);
printf("%d\n",Query_Max(_ , __ , 1 , n , 1) - Qmin(_ , __ , 1 , n , 1));
}
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  poj