程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> POJ 3264 Balanced Lineup 線段樹

POJ 3264 Balanced Lineup 線段樹

編輯:C++入門知識

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 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;
} 

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved