Balanced Lineup (POJ_3264) 线段树+区间查询

Balanced Lineup
Time Limit: 5000MS   Memory Limit: 65536K
Total Submissions: 42086   Accepted: 19775
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


题目大意:给出n个数,进行q次询问,求出每次询问区间中最大数和最小数绝对值之差。

解题思路:线段树,区间查询。

代码如下:
#include"iostream"
#include"cstdio"
#define MAX 0x7fffffff
using namespace std; 
const int maxn=50100;
struct Tree{
	int l,r,max,min;
	int getmid(){
		return (l+r)>>1;
	}
}tree[maxn*4];
void pushup(int x){
	int tmp=2*x;
	tree[x].max=(tree[tmp].max>tree[tmp+1].max)?tree[tmp].max:tree[tmp+1].max;
	tree[x].min=(tree[tmp].min<tree[tmp+1].min)?tree[tmp].min:tree[tmp+1].min;
}
void Build(int l,int r,int x){
	tree[x].l=l;
	tree[x].r=r;
	if(l==r){	//叶子节点 
		int t;
		scanf("%d",&t);
		tree[x].max=t;
		tree[x].min=t;
		return ;
	}
	int tmp=2*x;
	int mid=tree[x].getmid();
	Build(l,mid,tmp);
	Build(mid+1,r,tmp+1);
	pushup(x);
}
int _min,_max;
void Query(int l,int r,int x){
	if(r<tree[x].l||l>tree[x].r){
		return ;
	}
	if(l==tree[x].l&&tree[x].r==r){
		_max=_max>tree[x].max?_max:tree[x].max;
		_min=_min<tree[x].min?_min:tree[x].min;
		return ;
	}
	int mid=tree[x].getmid();
	int tmp=2*x;
	if(mid>=r)
		Query(l,r,tmp);
	else if(mid<l)
		Query(l,r,tmp+1);
	else{
		Query(l,mid,tmp);
		Query(mid+1,r,tmp+1);
	}
}
int main(){
	int n,q;
	while(scanf("%d%d",&n,&q)!=EOF){
		Build(1,n,1);
		while(q--){
			_min=MAX;
			_max=-MAX;
			int x,y;
			scanf("%d%d",&x,&y);
			Query(x,y,1);
			int ans=_max-_min;
			//printf("_max=%d,_min=%d\n",_max,_min);
			printf("%d\n",ans);
		}
	}
	return 0;
}





你可能感兴趣的:(线段树,poj,区间查询,区间更新)