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<stdio.h>
#include<queue>
#include<string.h>
#include<algorithm>
using namespace std;
#define ll long long
#define inf 0x3f3f3f3f
const int maxn=50000+5;
int t[maxn<<2],s[maxn<<2],sum[maxn<<2];
int maxx,minn;
void pushup(int rt)
{
    t[rt]=max(t[rt<<1],t[rt<<1|1]);
    s[rt]=min(s[rt<<1],s[rt<<1|1]);
}
void build(int l,int r,int rt)
{
    if(l==r)
    {
        scanf("%d",&sum[rt]);
        t[rt]=sum[rt];
        s[rt]=sum[rt];
        return ;
    }
    int m=(r+l)>>1;
    build(l,m,rt<<1);
    build(m+1,r,rt<<1|1);
    pushup(rt);
}
void queryt(int L,int R,int l,int r,int rt)
{
    if(L<=l&&r<=R)
    {
        maxx=max(maxx,t[rt]);
        return;
    }
    int m=(r+l)>>1;
    if(L<=m)
        queryt(L,R,l,m,rt<<1);
    if(R>m)
        queryt(L,R,m+1,r,rt<<1|1);
}
void querys(int L,int R,int l,int r,int rt)
{
    if(L<=l&&r<=R)
    {
        minn=min(minn,s[rt]);
        return;
    }
    int m=(r+l)>>1;
    if(L<=m)
        querys(L,R,l,m,rt<<1);
    if(R>m)
        querys(L,R,m+1,r,rt<<1|1);
}
int main()
{
    int n,q,a,b;
    while(~scanf("%d%d",&n,&q))
    {
        build(1,n,1);
        for(int i=0;i<q;i++)
        {
            scanf("%d%d",&a,&b);
        maxx=-1;
        minn=inf;
            queryt(a,b,1,n,1);
            querys(a,b,1,n,1);
            int ans=maxx-minn;
            printf("%d\n",ans);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/zezzezzez/article/details/80259103