POJ 3264(线段树区间查询求最大和最小值)

题目:Balanced Lineup
Time Limit: 5000MS Memory Limit: 65536K
Total Submissions: 70940 Accepted: 32816
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
#include
using namespace std;
const int inf=5e4+5;
int maxs[inf*4],mins[inf*4],a[inf];

void pushup(int rt)
{
	maxs[rt]=max(maxs[rt*2],maxs[rt*2+1]);
	mins[rt]=min(mins[rt*2],mins[rt*2+1]);
}
void build(int l,int r,int rt)
{
	if(l==r)
	{
		maxs[rt]=mins[rt]=a[l];
		return ;
	}
	int m=(l+r)/2;
	build(l,m,rt*2);
	build(m+1,r,rt*2+1);
	pushup(rt);
}
int query_max(int L,int R,int l,int r,int rt)
{
	if(L<=l&&r<=R)
	{
		return maxs[rt];
	}
	int m=(l+r)/2;
	int ans=-1;//做临时比较 
	if(L<=m) ans=max(ans,query_max(L,R,l,m,rt*2));
	if(R>m)  ans=max(ans,query_max(L,R,m+1,r,rt*2+1));
	
	return ans;
}
int query_min(int L,int R,int l,int r,int rt)
{
	if(L<=l&&r<=R)
	{
		return mins[rt];
	}
	int m=(l+r)/2;
	int ans=1000005;//做临时比较 
	if(L<=m) ans=min(ans,query_min(L,R,l,m,rt*2));
	if(R>m)  ans=min(ans,query_min(L,R,m+1,r,rt*2+1));
	
	return ans;
}

int main()
{
	int n,q,L,R;
	cin>>n>>q;
	for(int i=1;i<=n;i++)
	{
		scanf("%d",&a[i]);
	}
	build(1,n,1);
	while(q--)
	{
		scanf("%d %d",&L,&R);
		printf("%d\n",query_max(L,R,1,n,1)-query_min(L,R,1,n,1));
	}
	return 0;
}

你可能感兴趣的:(POJ 3264(线段树区间查询求最大和最小值))