E. MEX vs DIFF

题目链接 :Problem - E - Codeforces (Unofficial mirror site, accelerated for Chinese users)

题意:给定一个有n个元素的集合a(元素可以重复),定义DIFF为集合中元素种类, MEX为集合中未出现的最小自然数

给定一个操作 :将集合a中的一个元素变成任意一个自然数。

这个操作最多使用k次

求操作后 DIFF - MEX的最小值。

思路 : 枚举[0, n]中每一个值作为MEX,求ans

                假设x为当前MEX的值,则小于x的每个数都至少需要出现一次,若将小于MEX且出现多次的数转化成需要的数,因为其本身也需要至少出现一次,则DIFF一定加1(相对于答案来说)。而通过将大于等于MEX转化成需要的数,若其全部被转化,则DIFF将不变(相对于答案来说)。所以只考虑转移后面的数。

#include<bits/stdc++.h>
#include<unordered_map>
#define ll long long
#define ull unsigned long long
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace std;

const ll inf = 0x3f3f3f3f;
const double eps = 1e-4;
const int mod = 1e9 + 7;
const ll N = 1e5 + 5;

ll n, k;

void solve()
{
	map<ll, ll> cnt;
	cin >> n >> k;
	for (ll i = 0; i <= n; i++)
		cnt[i] = 0;//声明
	for (ll i = 1, x; i <= n; i++)
		cin >> x, cnt[x]++;
	
	ll nonzero = 0;
	for (auto [x, c] : cnt)
		nonzero += c > 0;

	priority_queue<ll> q;
	ll sum = 0, right = 0, ans = inf;
	for (auto it = cnt.rbegin(); it != cnt.rend(); it++)
	{
		auto [x, c] = *it;//将x作为MEX
		nonzero -= c > 0;
		right++;
		vector<ll> a{ c };//当前点的数量需变成0
		if (k >= x - nonzero)//是否能使得小于MEX的数都存在
		{
			while (q.size() && sum > k)//记录可移动的剩余数量(包括数量为0的)
			{
				a.push_back(q.top());
				sum -= q.top();
				q.pop();
			}
			ans = min(ans, (ll)(right - q.size() - 1));//right - q.size()为大于等于MEX的数字种类,-1为MEX
		}
		
		for (auto i : a)
		{
			q.push(i);
			sum += i;
		}
		while (sum > k)
		{
			sum -= q.top();
			q.pop();
		}
	}
	cout << ans << '\n';
}

signed main()
{
	IOS;
	//init();
	ll t = 1;
	cin >> t;
	while (t--)
		solve();
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值