51nod1686 第K大区间

链接:http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1686

题意:中文题。

分析:二分答案就行了。但是!有一个坑,k<=n*(n-1)/2。这是什么意思呢?意思是区间宽度至少为2,即[l,r]时l!=r。

代码:

#include<map>
#include<set>
#include<cmath>
#include<queue>
#include<bitset>
#include<math.h>
#include<cstdio>
#include<vector>
#include<string>
#include<cstring>
#include<iostream>
#include<algorithm>
#pragma comment(linker, "/STACK:102400000,102400000")
using namespace std;
const int N=100100;
const int MAX=151;
const int mod=100000000;
const int MOD1=1000000007;
const int MOD2=1000000009;
const double EPS=0.00000001;
typedef long long ll;
const ll MOD=998244353;
const ll INF=10000000010;
typedef double db;
typedef unsigned long long ull;
int n,a[N],b[N];
ll mul(ll x) {
    if (x<=0) return 0;
    return x*(x-1)/2;
}
ll cala(int x) {
    ll ret=0;
    int i,l=0,la=0;
    memset(b,0,sizeof(b));
    for (i=1;i<=n;i++) {
        b[a[i]]++;
        if (b[a[i]]>x) {
            ret+=mul(i-l-1);ret-=mul(la-l-1);
            while (b[a[i]]>x) { l++;b[a[l]]--; }
            la=i;
        }
    }
    ret+=mul(i-l-1);ret-=mul(la-l-1);
    return ret;
}
int main()
{
    int i,l,r,mid;
    ll k;
    scanf("%d%lld", &n, &k);
    for (i=1;i<=n;i++) {
        scanf("%d", &a[i]);b[i]=a[i];
    }
    sort(b+1,b+n+1);
    r=unique(b+1,b+n+1)-(b+1);
    for (i=1;i<=n;i++) a[i]=lower_bound(b+1,b+r+1,a[i])-b;
    k=mul(n)-k+1;
    l=0;r=n;mid=(l+r)/2;
    while (l+1<r)
    if (cala(mid)<k) { l=mid;mid=(l+r)/2; }
    else { r=mid;mid=(l+r)/2; }
    printf("%d\n", r);
    return 0;
}


你可能感兴趣的:(51nod1686 第K大区间)