欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

POJ-3264 Balanced Lineup

程序员文章站 2024-03-15 21:34:54
...

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 Ato 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<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int ma[220000],mi[220000];
void creat(int l,int r,int o)//建立树状树
{
    if(l==r)
    {
        scanf("%d",&ma[o]);
        mi[o]=ma[o];
        return ;
    }
    int mid=(r+l)>>1;
    creat(l,mid,o<<1);
    creat(mid+1,r,o<<1|1);
    ma[o]=max(ma[o<<1],ma[o<<1|1]);
    mi[o]=min(mi[o<<1],mi[o<<1|1]);
}
int ask1(int x,int y,int l,int r,int o)//最大值
{
    while(l>=x&&r<=y)
        return ma[o];
    int mid=(l+r)>>1;
    int t1=0,t2=0;
    if(x<=mid)
        t1=ask1(x,y,l,mid,o<<1);
    if(y>mid)
        t2=ask1(x,y,mid+1,r,o<<1|1);
    return max(t1,t2);
}
int ask2(int x,int y,int l,int r,int o)//最小值
{
    while(l>=x&&r<=y)
        return mi[o];
    int mid=(l+r)>>1;
    int t1=0x3f3f3f3f,t2=0x3f3f3f3f;
    if(x<=mid)
        t1=ask2(x,y,l,mid,o<<1);
    if(y>mid)
        t2=ask2(x,y,mid+1,r,o<<1|1);
    return min(t1,t2);
}
int main()
{
    int n,m;
    while(~scanf("%d",&n))
    {
        scanf("%d",&m);
        memset(ma,0,sizeof(ma));
        memset(mi,0,sizeof(mi));
        creat(1,n,1);
        while(m--)
        {
            int a,b;
            scanf("%d%d",&a,&b);
            int t1=ask1(a,b,1,n,1);
            int t2=ask2(a,b,1,n,1);
            printf("%d\n",t1-t2);
        }
    }
    return 0;
}

 

相关标签: 最大值和最小值