当前位置:编程学习 > C/C++ >>

POJ 3264 Balanced Lineup 线段树

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 易做图, 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 2Sample Output

6
3
0

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <climits>
using namespace std;
/*
int max(int a,int b){
	return a>b?a:b;
}*/
const int MAXN=50010; 
struct tnode {
	int l,r,mmax,mmin;
};
tnode node[MAXN*4];
int a[MAXN],maxv,minv;
void init(int k,int l,int r) // 节点k对应的区间为 [l,r) 
{
	node[k].l=l;
	node[k].r=r;
	if(r-l==1){          // 区间只有一个元素的情况 
		node[k].mmax=node[k].mmin=a[l];
		return ;
	} 
	int mid=(l+r)/2;
	init(2*k+1,l,mid);
	init(2*k+2,mid,r); //分别构造左右子树 
	node[k].mmax=max(node[2*k+1].mmax,node[2*k+2].mmax);
	node[k].mmin=min(node[2*k+1].mmin,node[2*k+2].mmin);
}
void query(int l,int r,int k)
{
	if(node[k].l==l && node[k].r==r ){ // 查询的区间和节点区间完全重合 
		maxv=max(maxv,node[k].mmax);
		minv=min(minv,node[k].mmin);
		return ;
	}
	int mid=(node[k].l+node[k].r)/2;
	if(mid<=l) query(l,r,2*k+2);     //所查询的区间在右子树 
	else if(mid>=r) query(l,r,2*k+1); //所查询的区间在左子树 
	else {
		query(l,mid,2*k+1);   //所查询的区间分别在左右子树上 
		query(mid,r,2*k+2);
	}
}
int main()
{
	int n,q;
	while(cin>>n>>q)
	{
		memset(node,0,sizeof(node));
		for(int i=0;i<n;i++) 
			scanf("%d",&a[i]);
		init(0,0,n);   //初始化线段树 
		for(int i=0;i<q;i++)
		{
			int x,y;
			scanf("%d %d",&x,&y);
			maxv=0;minv=INT_MAX;
			query(x-1,y,0);    //这里是左闭右开区间 
			cout<<maxv-minv<<endl;
		}
	}
	return 0;
} 

 

补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,