codeforces 6E.Exposition(RMQ+二分)

Exposition

Description
There are several days left before the fiftieth birthday of a famous Berland’s writer Berlbury. In this connection the local library decided to make an exposition of the works of this famous science-fiction writer. It was decided as well that it is necessary to include into the exposition only those books that were published during a particular time period. It is obvious that if the books differ much in size, the visitors will not like it. That was why the organizers came to the opinion, that the difference between the highest and the lowest books in the exposition should be not more than k millimeters.

The library has n volumes of books by Berlbury, arranged in chronological order of their appearance. The height of each book in millimeters is know, it is hi. As Berlbury is highly respected in the city, the organizers want to include into the exposition as many books as possible, and to find out what periods of his creative work they will manage to cover. You are asked to help the organizers cope with this hard task.

给一个n个元素的序列,从中挑出最长的子串,要求子串中元素差的最大值不超过k。问有几个最长子串,子串长度,以及这几个子串起始、终止位置。

Hint
首先区分子串与子序列的定义:

  • 某个数列的子序列是从最初序列通过去除某些元素但不破坏余下元素的相对位置(在前或在后)而形成的新数列
  • 如果子序列在原序列中是连续的,就称之为子串

即子串是连续的子序列不要求连续
本题思路:
既然要求子串中的最大值和最小值,我们可以想到用RMQ.
我们枚举子串的左端点l,然后二分右端点r,如果[l,r]中极差不大于k就继续向右二分.
单调性证明 右端点越向右,加入子串的元素越多,期望的极差也就越大

Code

#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
#define siz 100010
#define maxn(a,b) (a>b?a:b)
#define minn(a,b) (a<b?a:b)
using namespace std;
int n,k,l,r,mid,nans,cnt;
int a[siz],maxT[siz][20],minT[siz][20],ansl[siz][2];
inline int gmax(int l,int r) {
    int j=log2(r-l+1);
    return maxn(maxT[l][j],maxT[r-(1<<j)+1][j]);
}
inline int gmin(int l,int r) {
    int j=log2(r-l+1);
    return minn(minT[l][j],minT[r-(1<<j)+1][j]);
}
int binary_(int i) {
    l=i,r=n;
    int ans=i;
    while(l<=r) {
        mid=(l+r)>>1;
        if(gmax(i,mid)-gmin(i,mid)<=k) ans=mid,l=mid+1;
        else r=mid-1;
    }
    return ans;
}
int main ( ) {

    scanf("%d%d",&n,&k);
    for(int i=1;i<=n;++i) scanf("%d",&a[i]),maxT[i][0]=minT[i][0]=a[i];
    for(int j=1;(1<<j)<=n;++j)
     for(int i=1;(i+(1<<j)-1)<=n;++i) {
          maxT[i][j]=maxn(maxT[i][j-1],maxT[i+(1<<(j-1))][j-1]);
          minT[i][j]=minn(minT[i][j-1],minT[i+(1<<(j-1))][j-1]);
     }
    for(int i=1;i<=n;++i) {
        int pos=binary_(i); //printf("now nans=%d cnt=%d i=%d pos=%d\n",nans,cnt,i,pos);
        if(pos-i+1>nans) nans=pos-i+1,ansl[cnt=1][0]=i,ansl[cnt][1]=pos;
        else if(pos-i+1==nans) ansl[++cnt][0]=i,ansl[cnt][1]=pos;
    }    
    printf("%d %d\n",nans,cnt);
    for(int i=1;i<=cnt;++i) printf("%d %d\n",ansl[i][0],ansl[i][1]); 
    return 0;
}
posted @ 2018-04-10 16:25  Nepenthe  阅读(207)  评论(0)    收藏  举报


删边加边,浮生建模