Balanced Lineup - POJ/3264

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
题意: 第一行给定N、Q ,
接下来N行输入牛的高度,
接下来Q行输入查询的范围(左右边界),
要求输出查询范围内牛身高的 最大最小的差值。

思路:
1、运用线段树,将牛的身高建树;
2、查询出最大最小;
3、输出差值。

#include
#include
#include
#include
using namespace std;
#define lson 2*k,l,mid
#define rson 2*k+1,mid+1,r
const int MAXN = 50005;
const int inf = 0x3f3f3f;//表示无穷大
int a[MAXN],n_max[4*MAXN], n_min[MAXN*4]; 
void buildTree(int k,int l,int r)
{
	if(l == r)
	{
		n_max[k] = a[l];
		n_min[k] = a[l];
		return ;
	}
	int mid = (l+r)/2;
	buildTree(lson);
	buildTree(rson);
	n_max[k] = max(n_max[2*k], n_max[2*k+1]);
	n_min[k] = min(n_min[2*k], n_min[2*k+1]);
}
int query_max(int k,int l,int r,int ql,int qr)
{
	if(ql>r || qr<l)
	{
		return 0;
	}
	else if(ql<=l && r<=qr)
	{
		return n_max[k];
	}
	int mid=(l+r)/2;
	int s1 = query_max(lson,ql,qr);
	int s2 = query_max(rson,ql,qr);
	return max(s1,s2);
}
int query_min(int k,int l,int r,int ql,int qr)
{
	if(ql>r || qr<l)
	{
		return inf;
	}
	else if(ql<=l && r<=qr)
	{
		return n_min[k];
	}
	int mid=(l+r)/2;
	int s1 = query_min(lson,ql,qr);
	int s2 = query_min(rson,ql,qr);
	return min(s1,s2);
}
int main()
{
	int n,q;
	while(~scanf("%d%d",&n,&q))
	{
		for(int i=1;i<=n;i++)
		{
			scanf("%d",&a[i]);
		}
		buildTree(1,1,n);
		for(int j=1;j<=q;j++)
		{
			int x,y;
			scanf("%d%d",&x,&y);
			printf("%d\n",query_max(1,1,n,x,y) - query_min(1,1,n,x,y));
		}
	}	
	
	return 0;
} 

补充:

//无穷大,无穷小表示:
#define MaxN  0x3f3f3f3f
#define MinN  0xc0c0c0c0
		printf("%d %d\n",MaxN,MinN);
    	//1061109567, -1061109568

你可能感兴趣的:(线段树)