poj 3264 Balanced Lineup

来源:互联网 发布:wacom mac 笔记软件 编辑:程序博客网 时间:2024/06/05 10:03

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.. NQ+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 31734251 54 62 2
Sample Output
630


#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>#define maxn 50005using namespace std;struct node{int minn;int maxx;node (){maxx=0;minn=0;}};node Sum[maxn*4];int a[maxn],n,MAX=-1,MIN=1000005;void PushUp(int rt){Sum[rt].maxx=max(Sum[rt*2].maxx,Sum[rt*2+1].maxx);Sum[rt].minn=min(Sum[rt*2].minn,Sum[rt*2+1].minn);}void Build(int l,int r,int rt){if(l==r){Sum[rt].maxx=Sum[rt].minn=a[l];return;}int m=(l+r)/2;Build(l,m,rt*2);Build(m+1,r,rt*2+1);PushUp(rt);}void Query(int L,int R,int l,int r,int rt){if(L<=l&&r<=R){if(Sum[rt].maxx>MAX)MAX=Sum[rt].maxx;if(Sum[rt].minn<MIN)MIN=Sum[rt].minn;return ;}int m=(l+r)/2;if(L<=m)Query(L,R,l,m,rt*2);if(R>m)Query(L,R,m+1,r,rt*2+1);}int main(){int T,L,R;scanf("%d%d",&n,&T);for(int i=1;i<=n;i++)scanf("%d",&a[i]);Build(1,n,1);while(T--){MAX=-1;MIN=1000005;scanf("%d%d",&L,&R);Query(L,R,1,n,1);printf("%d\n",MAX-MIN);}return 0;}






原创粉丝点击