POJ-3264 Balanced Lineup(线段树代码讲解很详细)

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个高度值,然后有m个区间,求每个区间内最大值与最小值的差。
解题思路:线段树求区间最值模板。
AC代码如下:

#include
#include
#include
#define lson rt<<1//左子数
#define rson rt<<1|1//右子树
using namespace std;
int sum1[500000],sum2[500000];//sum1用来存储当前区间的最小值,sum2用来存储当前区间的最大值
void pushup(int rt){//状态合并,用左右子区间的值来更新当前区间的值
	sum1[rt]=min(sum1[lson],sum1[rson]);
	sum2[rt]=max(sum2[lson],sum2[rson]);
}
void build(int rt,int l,int r){//建树
	if(l==r){//递归到了叶子节点
		scanf("%d",&sum1[rt]);
		sum2[rt]=sum1[rt];
		return ;
	}
	int mid=(l+r)>>1;
	build(lson,l,mid);//递归到左子区间
	build(rson,mid+1,r);//递归到右子区间
	pushup(rt);//状态合并,用左右子区间所对应的值更新当前区间的值
}
int query1(int rt,int L,int R,int l,int r){//查询给定区间的最小值
	if(l>=L&&r<=R){
		return sum1[rt];
	}
	int mid=(l+r)>>1,minn=999999999;
	if(L<=mid) 
		minn=min(minn,query1(lson,L,R,l,mid));
	if(R>mid){
		minn=min(minn,query1(rson,L,R,mid+1,r));
	}
	return minn;
}
int query2(int rt,int L,int R,int l,int r){//查询给定区间的最大值
	if(l>=L&&r<=R){
		return sum2[rt];
	}
	int mid=(l+r)>>1,maxx=-1;
	if(L<=mid) 
		maxx=max(maxx,query2(lson,L,R,l,mid));
	if(R>mid){
		maxx=max(maxx,query2(rson,L,R,mid+1,r));
	}
	return maxx;
}
int main(){
	int n,m,x,y;
	while(~scanf("%d%d",&n,&m)){
		build(1,1,n);
		while(m--){
			scanf("%d%d",&x,&y);
			printf("%d\n",query2(1,x,y,1,n)-query1(1,x,y,1,n));//计算给定区间最大值与最小值的差
		}
	}
	return 0;
}

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