【求区间最大最小值】Balanced Lineup POJ - 3264

Balanced Lineup POJ - 3264

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 3
1
7
3
4
2
5
1 5
4 6
2 2

Sample Output

6
3
0
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn=5e4+5;
int n,m,x,y,height;
struct node
{
    int t,s;
}tree[maxn*4];

void build(int l,int r,int rt)
{
    if(l==r)
    {
        scanf("%d",&height);
        tree[rt].t=tree[rt].s=height;
        return;
    }
    int mid=(l+r)/2;
    build(l,mid,2*rt);
    build(mid+1,r,2*rt+1);
    tree[rt].t=max(tree[rt*2].t,tree[rt*2+1].t);
    tree[rt].s=min(tree[rt*2].s,tree[rt*2+1].s);
}

int query_tall(int L,int R,int l,int r,int rt)
{
    if(L<=l&&R>=r)
    {
        return tree[rt].t;
    }
    int mid=(l+r)/2;
    int left=0,right=0;
    if(L<=mid) left=max(left,query_tall(L,R,l,mid,2*rt));
    if(R>mid) right=max(right,query_tall(L,R,mid+1,r,2*rt+1));
    return max(left,right);
}

int query_short(int L,int R,int l,int r,int rt)
{
    if(L<=l&&R>=r)
    {
        return tree[rt].s;
    }
    int mid=(l+r)/2;
    int left=1e7,right=1e7;
    if(L<=mid) left=min(left,query_short(L,R,l,mid,2*rt));
    if(R>mid) right=min(right,query_short(L,R,mid+1,r,2*rt+1));
    return min(left,right);
}

int main()
{
    scanf("%d%d",&n,&m);
    build(1,n,1);
    for(int i=1;i<=m;i++)
    {
        scanf("%d%d",&x,&y);
        printf("%d\n",query_tall(x,y,1,n,1)-query_short(x,y,1,n,1));
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41037114/article/details/81190791