Codeforces Beta Round #6 (Div. 2 Only) E. Exposition

题解:
主要是运用线段树查询区间最大值和最小值,然后用尺取法去找满足条件的区间。

#include 
#include 
#include 
#include 

#define FOR(i,a,b) for(int i=a;i<=b;i++)
#define ROF(i,a,b) for(int i=a;i>=b;i--)
#define mem(i,a) memset(i,a,sizeof(i))
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
using namespace std;
const int maxn = 1e5+5;
int n,k,cnt=0,tmp=1;
int h[maxn<<2],mx[maxn<<2],mi[maxn<<2];
struct node{
    int l,r;
}ans[maxn<<2];

void pushup(int rt){
    mx[rt] = max(mx[rt<<1],mx[rt<<1|1]);
    mi[rt] = min(mi[rt<<1],mi[rt<<1|1]);
}

void build(int l,int r,int rt){
    if(l == r){
        scanf("%d",&h[l]);
        mx[rt] = mi[rt] = h[l];
        return ;
    }
    int mid = (l+r)/2;
    build(lson);
    build(rson);
    pushup(rt);
}

int querym(int l,int r,int rt,int L,int R){
    if(l>=L&&r<=R) return mx[rt];
    int mid = (l+r)/2;
    int ans=0;
    if(mid>=L) ans = max(ans,querym(lson,L,R));
    if(midreturn ans;
}

int queryi(int l,int r,int rt,int L,int R){
    if(l>=L&&r<=R) return mi[rt];
    int mid = (l+r)/2;
    int ans=0x7fffffff;
    if(mid>=L) ans = min(ans,queryi(lson,L,R));
    if(midreturn ans;
}

int main()
{
    scanf("%d%d",&n,&k);
    build(1,n,1);

    int l=1,r=1;
    while(l<=n){
        int fx = querym(1,n,1,l,r);
        int fy = queryi(1,n,1,l,r);
        if(fx>=fy){
            if(fx-fy<=k){
                if(r-l+1==tmp){
                    ans[cnt].l = l;
                    ans[cnt].r = r;
                    cnt++;
                }else if(r-l+1>tmp){
                    cnt=0;
                    tmp = r-l+1;
                    ans[cnt].l = l;
                    ans[cnt].r = r;
                    cnt++;
                }
                r++;
            }else l++;
        }else l++;
        if(r>n) r=n,l++;
        if(l>=r) r=l;
        if(r>n)break;
    }
    printf("%d %d\n",tmp,cnt);
    FOR(i,0,cnt-1){
        printf("%d %d\n",ans[i].l,ans[i].r);
    }
    return 0;
}

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