来源:牛客网
题目描述
The mode of an integer sequence is the value that appears most often. Chiaki has n integers
a1,a2,...,an
a
1
,
a
2
,
.
.
.
,
a
n
. She woud like to delete exactly m of them such that: the rest integers have only one mode and the mode is maximum.
输入描述:
There are multiple test cases. The first line of input contains an integer T, indicating the number of test cases. For each test case:
The first line contains two integers n and m
(1≤n≤105,0≤m<n)
(
1
≤
n
≤
10
5
,
0
≤
m
<
n
)
– the length of the sequence and the number of integers to delete.
The second line contains n integers
a1,a2,...,an(1≤ai≤109)
a
1
,
a
2
,
.
.
.
,
a
n
(
1
≤
a
i
≤
10
9
)
denoting the sequence.
It is guaranteed that the sum of all n does not exceed
106
10
6
.
输出描述:
For each test case, output an integer denoting the only maximum mode, or -1 if Chiaki cannot achieve it.
示例1
输入
5
5 0
2 2 3 3 4
5 1
2 2 3 3 4
5 2
2 2 3 3 4
5 3
2 2 3 3 4
5 4
2 2 3 3 4
输出
-1
3
3
3
4
我的做法好像有点复杂啊。先离散化,然后,统计每个离散化后出现的数字
num
n
u
m
的个数,再给这些个数
count
c
o
u
n
t
从小大排序,从
num
n
u
m
最大的开始验证,验证是如果答案是
numi
n
u
m
i
,那么个数设为
counti
c
o
u
n
t
i
,那么所以比
counti
c
o
u
n
t
i
大的值都必须降低到
counti−1
c
o
u
n
t
i
−
1
,这是最低值,那么我们就可以验证了,这里就是二分在加上前缀和了
代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<map>
#define maxx 100005
using namespace std;
int n,m;
int a[maxx];
int id[maxx];
int cnt,num;
int get(int x)
{
int l=1,r=num;
while(l<=r)
{
int mid=(l+r)>>1;
if(id[mid]==x) return mid;
if(id[mid]<x) l=mid+1;
else r=mid-1;
}
return 0;
}
int b[maxx];
int order[maxx];
int sum[maxx];
int tot;
int _get(int x)
{
int l=1,r=tot;
while(l<=r)
{
int mid=(l+r)>>1;
if(order[mid]>=x) r=mid-1;
else l=mid+1;
}
return l;
}
void init()
{
cnt=0;
tot=0;
memset(b,0,sizeof(b));
}
int main()
{
int t;
cin>>t;
while(t--)
{
init();
scanf("%d%d",&n,&m);
for(int i=0;i<n;i++)
scanf("%d",a+i),id[++cnt]=a[i];
num=unique(id+1,id+cnt+1)-id-1;
sort(id+1,id+num+1);
for(int i=0;i<n;i++) a[i]=get(a[i]);//离散化
for(int i=0;i<n;i++) b[a[i]]++;//统计个数
for(int i=1;i<=num;i++)
if(b[i])order[++tot]=b[i];//把个数收集起来
sort(order+1,order+1+tot);
for(int i=1;i<=tot;i++)
sum[i]=sum[i-1]+order[i];//前缀和
bool sign=false;
int ans;
for(int i=num;i>0;i--)
{
int index=_get(b[i]);//二分去找边界,就是找到所有大于等于b[i]的最小值
int total=sum[tot]-sum[index];
if(total-(b[i]-1)*(tot-index)<=m)//验证
{
//cout<<"xixi: "<<total-(b[i]-1)*(tot-index)<<endl;
ans=id[i];
sign=true;
break;
}
}
if(sign)printf("%d\n",ans);
else printf("-1\n");
}
return 0;
}