Newcoder 142 G.Maximum Mode(BIT)

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 &lt; n , 1 ≤ a i ≤ 1 0 9 ) (1\le T\le 10^5,0\le m&lt;n,1\le a_i\le 10^9) (1T105,0m<n,1ai109)

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 x1的数字数量之和 s u m sum sum以及这些数字的种类数 n u m num num,那么使得 a a a为众数至少需要把这 s u m − x ⋅ n u m sum-x\cdot num sumxnum个数字删掉,故 s u m − x ⋅ n u m ≤ m sum-x\cdot num\le m sumxnumm 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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值