您的位置:首页 > 其它

POJ3264(线段树求区间最大值和最小值)

2015-05-28 13:09 393 查看
Balanced Lineup

Time Limit: 5000MSMemory Limit: 65536K
Total Submissions: 38054Accepted: 17819
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

题目大意:

给定一群羊,再给定一个区间,求区间中最大值 - 最小值是多少,本题如果有朴素暴力做,肯定会超时,就连我用线段树+cin都不能过,要改为scanf。

AC代码:

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

const int INF = 0xfffffff;
const int maxnode = 50001 * 4;

int op,qL,qR,p,v; //qL和qR为全局变量,询问区间[qL,qR];

struct IntervalTree
{
int minv[maxnode];
int maxv[maxnode];

void update(int o,int L,int R)
{
int M = L + (R - L) / 2;
if(L == R)
{
minv[o] = v;
maxv[o] = v;
}
else
{
if(p <= M) update(o * 2,L,M);
else
update(o * 2 + 1,M+1,R);
minv[o] = min(minv[o * 2],minv[o * 2 + 1]);
maxv[o] = max(maxv[o * 2],maxv[o * 2 + 1]);
}
}

int QueryMin(int o,int L,int R)
{
int M = L +(R - L) / 2, ans = INF;
if(qL <= L && R <= qR) return minv[o];
if(qL <= M) ans = min(ans,QueryMin(o * 2,L,M));
if(M < qR) ans = min(ans,QueryMin(o * 2 + 1,M+1,R));
return ans;
}

int QueryMax(int o,int L,int R)
{
int M = L +(R - L) / 2, ans = -INF;
if(qL <= L && R <= qR) return maxv[o];
if(qL <= M) ans = max(ans,QueryMax(o * 2,L,M));
if(M < qR) ans = max(ans,QueryMax(o * 2 + 1,M+1,R));
return ans;
}
};

IntervalTree tree;
int main()
{
int m,n;
int i;
//freopen("111","r",stdin);
while(cin>>m>>n)
{
memset(&tree, 0, sizeof(tree));
for(i=1;i<=m;i++)
{
p = i;
scanf("%d",&v);
tree.update(1,1,m);
}
for(i=1;i<=n;i++)
{
scanf("%d%d",&qL,&qR);
printf("%d\n",tree.QueryMax(1,1,m) - tree.QueryMin(1,1,m));
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: