POJ 2823 Sliding Window

//这是一道区间求最大值和最小值的题,模板题//

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=10000005;
int sum[MAX>>2];
int cnt[MAX>>2];
void pushup(int rt)
{
    sum[rt]=min(sum[rt<<1],sum[rt<<1|1]);
}
void Pushup(int rt)
{
    cnt[rt]=max(cnt[rt<<1],cnt[rt<<1|1]);
}
void build(int l,int r,int rt)
{
    if(l==r)
    {
        scanf("%d",&sum[rt]);
        cnt[rt]=sum[rt];
        return;
    }
    int m=(l+r)>>1;
    build(lson);
    build(rson);
    pushup(rt);
    Pushup(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=min(t,querty(L,R,lson));
    if(R>m)
        t=min(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=max(t,Querty(L,R,lson));
    if(R>m)
        t=max(t,Querty(L,R,rson));
    return t;
}
int main()
{
    int n,k;
    scanf("%d%d",&n,&k);
    build(1,n,1);
    for(int i=1;i<=n-k+1;i++)
    {
        if(i==1)
        {
            printf("%d",querty(i,i+k-1,1,n,1));
        }
        else
        {
             printf(" %d",querty(i,i+k-1,1,n,1));
        }
    }
    printf("\n");
    for(int i=1;i<=n-k+1;i++)
    {
        if(i==1)
        {
            printf("%d",Querty(i,i+k-1,1,n,1));
        }
        else
        {
             printf(" %d",Querty(i,i+k-1,1,n,1));
        }
    }
    return 0;
}

你可能感兴趣的:(POJ 2823 Sliding Window)