Description
给出 n n n个数 a 1 , . . . , a n a_1,...,a_n a1,...,an,要求删除其中 m m m个数字使得剩余数字的众数只有一个且其值最大
Input
第一行一整数 T T T表示用例组数,每组用例首先输入两个整数 n , m n,m n,m,之后输入 n n n个整数 a 1 , . . . , a n a_1,...,a_n a1,...,an
( 1 ≤ T ≤ 1 0 5 , 0 ≤ m < n , 1 ≤ a i ≤ 1 0 9 ) (1\le T\le 10^5,0\le m<n,1\le a_i\le 10^9) (1≤T≤105,0≤m<n,1≤ai≤109)
Output
如果众数必然超过一个则输出 − 1 -1 −1,否则输出众数的最大值
Sample Input
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
Sample Output
-1
3
3
3
4
Solution
枚举答案 a a a,假设 a a a出现次数为 x x x,那么需要统计所有数量超过 x − 1 x-1 x−1的数字数量之和 s u m sum sum以及这些数字的种类数 n u m num num,那么使得 a a a为众数至少需要把这 s u m − x ⋅ n u m sum-x\cdot num sum−x⋅num个数字删掉,故 s u m − x ⋅ n u m ≤ m sum-x\cdot num\le m sum−x⋅num≤m时 a a a可以为众数,否则不行,而 s u m sum sum和 n u m num num只需分别用两个树状数组维护,对于出现次数为 y y y的一个数字,在维护 s u m sum sum的树状数组的 y y y位置插入 y y y,在维护 n u m num num的树状数组的 y y y位置插入 1 1 1即可
Code
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<map>
using namespace std;
typedef pair<int,int>P;
#define maxn 100005
struct BIT
{
#define lowbit(x) (x&(-x))
int b[maxn],n;
void init(int _n)
{
n=_n;
for(int i=1;i<=n;i++)b[i]=0;
}
void update(int x,int v)
{
while(x<=n)
{
b[x]+=v;
x+=lowbit(x);
}
}
int query(int x)
{
int ans=0;
while(x)
{
ans+=b[x];
x-=lowbit(x);
}
return ans;
}
}sum,num;
map<int,int>M;
P a[maxn];
int T,n,m;
int main()
{
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m);
M.clear();
int res=0;
for(int i=1;i<=n;i++)
{
int x;
scanf("%d",&x);
if(M.find(x)==M.end())M[x]=++res,a[res].first=x,a[res].second=0,res;
a[M[x]].second++;
}
sum.init(n);
num.init(n);
for(int i=1;i<=res;i++)
{
sum.update(a[i].second,a[i].second);
num.update(a[i].second,1);
}
int ans=-1;
for(int i=1;i<=res;i++)
{
int tsum=sum.query(n)-sum.query(a[i].second-1)-a[i].second;
int tnum=num.query(n)-num.query(a[i].second-1)-1;
tsum-=tnum*(a[i].second-1);
if(tsum<=m)ans=max(ans,a[i].first);
}
printf("%d\n",ans);
}
return 0;
}