線段樹——Balanced Lineup

線段樹——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

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<iostream>
using namespace std;
#define maxn 50050
#define INF 0x3f3f3f3f
int f[maxn];
struct node{
	int l,r,mx,mn;
}a[maxn*4];
void build(int k,int l,int r)
{
	a[k].l=l;
	a[k].r=r;
	a[k].mn=0;
	a[k].mx=0;
	if(l==r){
		a[k].mx=f[l];
		a[k].mn=f[l];
		return ;
	}
	int mid=(l+r)/2;
	build(k*2,l,mid);
	build(k*2+1,mid+1,r);
	a[k].mx=max(a[k*2].mx,a[k*2+1].mx);
	a[k].mn=min(a[k*2].mn,a[k*2+1].mn);
}
int query_min(int k,int l,int r)
{
	if(a[k].l==l&&a[k].r==r){
		return a[k].mn;
	}
	int mid=(a[k].l+a[k].r)/2;
	int hmin=INF;
	if(r<=mid){
		 hmin=min(hmin,query_min(k*2,l,r));
	}
	else if(l>mid){
		hmin=min(hmin,query_min(k*2+1,l,r));
	}
	else{
		hmin=min(hmin,query_min(k*2,l,mid));
		hmin=min(hmin,query_min(k*2+1,mid+1,r));
	}
	return hmin;
}
int query_max(int k,int l,int r)
{
	if(a[k].l==l&&a[k].r==r){
		return a[k].mx;
	}
	int mid=(a[k].l+a[k].r)/2;
	int hmax=0;
	if(r<=mid){
		hmax=max(hmax,query_max(k*2,l,r));
	}
	else if(l>mid){
		hmax=max(hmax,query_max(k*2+1,l,r));
	}
	else{
		hmax=max(hmax,query_max(k*2,l,mid));
		hmax=max(hmax,query_max(k*2+1,mid+1,r));
	}
	return hmax;
}
int main()
{
	int n,q;
	scanf("%d%d",&n,&q);
	for(int i=1;i<=n;i++){
		scanf("%d",&f[i]);
	}
	build(1,1,n);
	for(int i=0;i<q;i++){
		int a,b;
		scanf("%d%d",&a,&b);
		printf("%d\n",query_max(1,a,b)-query_min(1,a,b));
	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章