链接:https://www.nowcoder.com/acm/contest/142/G
来源:牛客网
题目描述
The mode of an integer sequence is the value that appears most often. Chiaki has n integers a1,a2,...,an. 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) -- the length of the sequence and the number of integers to delete. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) denoting the sequence. It is guaranteed that the sum of all n does not exceed 106.
输出描述:
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
mode的定义:一个序列中出现最多次数的数值。删掉m个数之后,使mode尽可能大。
思路:
以某个数x当做最后答案唯一的限制条件是当前序列没有比x个数多的数。枚举每一个序列中出现的数值为答案,看能否删除比当前答案出现次数多的数,如果能,作为备选答案,比较答案最大值。m>要删除的数,要求多删的数随便删就可以了。
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+100;
int a[N],d[N];
struct Node
{
int num;
int value;
bool operator <(const Node&other) const
{
return num>other.num;
}
}node[N];
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
int n,m,i,j;
scanf("%d%d",&n,&m);
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
sort(a+1,a+n+1);
int cnt=1;
memset(node,0,sizeof(node));
node[1].num=1;node[1].value=a[1];
for(i=2;i<=n;i++)
{
if(a[i-1]!=a[i])
{
node[++cnt].num=1;
node[cnt].value=a[i];
}
else
{
node[cnt].num++;
}
}
sort(node+1,node+n+1);
int t=1;
for(i=1;i<=cnt;i++)
{
if(node[i-1].num==node[i].num&&i>=1)
d[node[i].num]++;
else
d[node[i].num]=1;
}
int del=0,tt=-1;
int ans=-1;
for(i=1;i<=cnt;i++)
{
if(node[i-1].num>node[i].num&&i>=1)
{
del+=(node[i-1].num-node[i].num)*d[node[i-1].num];
d[node[i].num]+=d[node[i-1].num];
}
tt=del+d[node[i].num]-1;
if(m>=tt)
ans=max(ans,node[i].value);
}
printf("%d\n",ans);
}
return 0;
}