poj 3264 Balanced Lineup(线段树 区间最值)

来源:互联网 发布:淘宝店铺推广平台 编辑:程序博客网 时间:2024/05/22 02:03
Balanced Lineup
Time Limit: 5000MS Memory Limit: 65536KTotal Submissions: 56516 Accepted: 26478Case Time Limit: 2000MS

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 31734251 54 62 2

Sample Output

630
tips:线段树
#include<iostream>#include<cstring>#include<cstdio>using namespace std;const int maxn=55555;const int maxh=1111111;int MAX[maxn<<2];int MIN[maxn<<2];int n,q;void pushup(int rt){MAX[rt]=max(MAX[rt<<1],MAX[rt<<1|1]);MIN[rt]=min(MIN[rt<<1],MIN[rt<<1|1]);}void build(int rt,int l,int r){if(l==r){scanf("%d",MAX+rt);MIN[rt]=MAX[rt];return;}int m=(l+r)>>1;build(rt<<1,l,m);build(rt<<1|1,m+1,r);pushup(rt); }int query1(int rt,int l,int r,int ll,int rr){if(ll<=l&&rr>=r){return MAX[rt];}int m=(l+r)>>1;int ret=0;if(ll<=m)ret=max(ret,query1(rt<<1,l,m,ll,rr));if(rr>m)ret=max(ret,query1(rt<<1|1,m+1,r,ll,rr));return ret;}int query2(int rt,int l,int r,int ll,int rr){if(ll<=l&&rr>=r){return MIN[rt];}int m=(l+r)>>1;int ret=0x7fffffff;if(ll<=m)ret=min(ret,query2(rt<<1,l,m,ll,rr));if(rr>m)ret=min(ret,query2(rt<<1|1,m+1,r,ll,rr));return ret;}int main(){cin>>n>>q;build(1,1,n);while(q--){int x,y;scanf("%d %d",&x,&y);printf("%d\n",query1(1,1,n,x,y)-query2(1,1,n,x,y));}return 0;}