poj2823线段树

简单的区间求和
g++超时 c++过

#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
using namespace std;

const int MAXN=1000005;
int MIN[MAXN<<2];
int MAX[MAXN<<2];
int MINS[MAXN<<2];
int MAXS[MAXN<<2];

void build(int l,int r,int rt)
{
    if(l==r)
    {
        scanf("%d",&MAX[rt]);
        MIN[rt]=MAX[rt];
        return ;
    }
    int m=(l+r)>>1;
    build(l,m,rt<<1);
    build(m+1,r,rt<<1|1);
    MIN[rt]=min(MIN[rt<<1],MIN[rt<<1|1]);
    MAX[rt]=max(MAX[rt<<1],MAX[rt<<1|1]);
}

int search_min(int ll,int rr,int l,int r,int rt)
{
    int minn=1e7;
    if(ll<=l&&rr>=r)
    {
        return MIN[rt];
    }
    int m=(l+r)>>1;
    if(ll<=m)
    minn=min(minn,search_min(ll,rr,l,m,rt<<1));
    if(rr>m)
    minn=min(minn,search_min(ll,rr,m+1,r,rt<<1|1));
    return minn;
}

int search_max(int ll,int rr,int l,int r,int rt)
{
    int maxx=-1e7;
    if(ll<=l&&rr>=r)
    {
        return MAX[rt];
    }
    int m=(l+r)>>1;
    if(ll<=m)
    maxx=max(maxx,search_max(ll,rr,l,m,rt<<1));
    if(rr>m)
    maxx=max(maxx,search_max(ll,rr,m+1,r,rt<<1|1));
    return maxx;
}

int main()
{
    int n,k;
    while(scanf("%d%d",&n,&k)!=-1)
    {
        int t=0;
        build(1,n,1);
        for(int i=1;i<=n-k+1;i++)
        {
            MAXS[t]=search_max(i,i+k-1,1,n,1);
            MINS[t]=search_min(i,i+k-1,1,n,1);
            t++;
        }
        for(int i=0;i<t;i++)
        printf("%d ",MINS[i]);
        printf("\n");
        for(int i=0;i<t;i++)
        printf("%d ",MAXS[i]);
        printf("\n");
    }
    return 0;
}

你可能感兴趣的:(poj2823线段树)