POJ 3264 Balanced Lineup

//典型的RMQ问题//

AC代码:

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
const int MAX=50005;
int sum[MAX<<2];
int cnt[MAX<<2];
void push(int rt)
{
    sum[rt]=max(sum[rt<<1],sum[rt<<1|1]);
}
void Push(int rt)
{
    cnt[rt]=min(cnt[rt<<1],cnt[rt<<1|1]);
}
void build(int l,int r,int rt)
{
    if(l==r)
    {
        scanf("%d",&cnt[rt]);
        sum[rt]=cnt[rt];
        return;
    }
    int m=(l+r)>>1;
    build(lson);
    build(rson);
    Push(rt);
    push(rt);
}
int querty(int L,int R,int l,int r,int rt)
{
    if(L<=l&&R>=r)
    {
        return sum[rt];
    }
    int m=(l+r)>>1;
    int t=-1<<29;
    if(L<=m)
        t=max(t,querty(L,R,lson));
    if(R>m)
        t=max(t,querty(L,R,rson));
    return t;
}
int Querty(int L,int R,int l,int r,int rt)
{
    if(L<=l&&R>=r)
    {
        return cnt[rt];
    }
    int m=(l+r)>>1;
    int t=1<<29;
    if(L<=m)
        t=min(t,Querty(L,R,lson));
    if(R>m)
        t=min(t,Querty(L,R,rson));
    return t;
}
int main()
{
    int n,m;
    scanf("%d%d",&n,&m);
    build(1,n,1);
    int i;
    int x,y;
    for(i=0;i<m;i++)
    {
        scanf("%d%d",&x,&y);
        printf("%d\n",querty(x,y,1,n,1)-Querty(x,y,1,n,1));
    }
    return 0;
}

你可能感兴趣的:(POJ 3264 Balanced Lineup)