poj3264 线段树维护最大值最小值

用线段树来维护区间的最大值最小值  
建好线段树,就可以针对查询来查出最大值最小值 

从而求出其差值

	#include 
	#include 
	#include 
	#include 
	#include 
	#include 
	#include 
	#include 
	#include 
	#include 
	#include 
	#include 
	#include 
	#define mem(a) memset(a,0,sizeof(a));
	#define mem_1(a) memset(a,-1,sizeof(a));
	#define sf(a) scanf("%d",&a)
	#define sff(a,b) scanf("%d%d",&a,&b)
	#define sfff(a,b,c) scanf("%d%d%d",&a,&b,&c)
	#define lson l,mid,i<<1
	#define rson mid+1,r,i<<1|1
	const int INF = 0x7FFFFFFF;
	const int MAXN = 50100;
	const double PI = acos(-1.0);
	const double esp = 1e-10;
	using namespace std;
	struct node
	{
		int l,r,Max,Min;
	}Tree[MAXN<<2];
	int xx;
	int MAX,MIN;
	void build_tree(int l,int r,int i)
	{
		Tree[i].l = l;
		Tree[i].r = r;
		if(l == r)
		{
			sf(xx);
			Tree[i].Max = Tree[i].Min = xx;
			return ;
		}
		int mid = (l+r)>>1;
		build_tree(lson);
		build_tree(rson);
		Tree[i].Max = max(Tree[i<<1].Max,Tree[i<<1|1].Max);
		Tree[i].Min = min(Tree[i<<1].Min,Tree[i<<1|1].Min);
	}
	void Query(int l,int r,int i)
	{
		if(Tree[i].l == l && Tree[i].r ==r)
		{
			MAX = max(MAX,Tree[i].Max);
			MIN = min(MIN,Tree[i].Min);
			return ;
		}
		int mid = (Tree[i].l + Tree[i].r) >>1;
		if(r <= mid) Query(l,r,i<<1);
		else if(mid < l) Query(l,r,i<<1|1);
		else
		{
			Query(lson);
			Query(rson);
		}
	}
	int main()
	{
		int n,m,x,y;

		sff(n,m);
		build_tree(1,n,1);
		while(m--)
		{
			sff(x,y);
			MAX = -1;
			MIN = INF;
			Query(x,y,1);
			printf("%d\n",MAX - MIN);
		}
	}


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