51nod 第K大区间

被杜教虐疯了= =

做了一天的不可做题决定刷刷水放松下心情

维护下数组单调性二分答案就可以了,LL实在是吭爹

/* ***********************************************
Author        :BPM136
Created Time  :2016/3/30 19:11:09
File Name     :OI\51Nod\running12\A.cpp
************************************************ */

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#include<set>
#include<map>
#include<string>
#include<math.h>
#include<stdlib.h>
#include<time.h>
#define LL long long
#define fo(i,a,b) for(int i=a;i<=b;i++)
#define fd(i,a,b) for(int i=a;i>=b;i--)
#define efo(i,x) for(int i=last[x];i!=0;i=e[i].next)
using namespace std;
LL read()
{
     LL d=0,f=1;char s=getchar();
     while(s<48||s>57){if(s==45)f=-1;s=getchar();}
     while(s>=48&&s<=57){d=d*10+s-48;s=getchar();}
     return d*f;
}
#define N 100005
LL n,m;
int a[N];
int B[N];
int C[N];
int ans=0;

int ma;int cnt[N],c[N];
void add(int x)
{
	--cnt[c[x]];c[x]++;cnt[c[x]]++;
	ma=max(ma,c[x]);
}

void dec(int x)
{
	--cnt[c[x]];c[x]--;cnt[c[x]]++;
	while(!cnt[ma])ma--;
}

bool check(int x)
{
	memset(cnt,0,sizeof(cnt));
	memset(c,0,sizeof(c));
	cnt[0]=n;ma=0;
	LL ret=0;
	int l=1;
	fo(i,1,n)
	{
		add(C[i]);
		while(l<=i)
		{
			dec(C[l]);
			if(ma<x)
			{
				add(C[l]);
				break;
			}
			l++;
		}
		if(ma>=x)ret+=l;
	}
	return ret>=m?1:0;
}

int EF(int l,int r)
{
	int ret=0;
	while(l<=r)
	{
		int mid=(l+r)>>1;
		if(check(mid))
		{
			l=mid+1;
			ret=mid;
		}else r=mid-1;
	}
	return ret;
}

int EFfind(int x,int l,int r)
{
	int mid=(l+r)>>1;
	if(x<B[mid])return EFfind(x,1,mid-1);
	if(x>B[mid])return EFfind(x,mid+1,r);
	if(x==B[mid])return mid;
}

int find(int x)
{
	int ret=EFfind(x,1,n);
	return ret;
}

int main()
{
    //freopen(".in","r",stdin);
    //freopen(".out","w",stdout);
    n=read();m=read();
    fo(i,1,n)
    {
	    a[i]=read();
	    B[i]=a[i];
    }
    sort(B+1,B+n+1);
    int temp=unique(B+1,B+n+1)-B;
    fo(i,1,n)C[i]=find(a[i]);
    ans=EF(1,n);
    cout<<ans<<endl;
    return 0;
}


你可能感兴趣的:(二分答案)