D. Jellyfish and Mex Codeforces Round 901 (Div. 2)

Problem - D - Codeforces

题目大意:有一个n个数的数组a,数m初始为0,每次操作可以删除任意一个数,然后m加上那个数,求n次操作和m的最小值

1<=n<=5000;0<=ai<=1e9

思路:可以发现,如果我们要删除某个数,那么一定要把所有和这个数相等的数全部删去,这样才能使MEX变小,同时,所有大于MEX的数删去的花费都是0,所以我们每次操作的数的大小都是递减的,且只会操作MEX到0。

那么我们令dpi等于MEX等于i时的最小花费,我们从MEX到0枚举i,同时枚举该删哪个数,也就是从0到i-1遍历,当前最小花费就是不删这个数dpj,或者删这个数也就是dpi+当前MEX*(这个数数量-1)再加这个数,转移方程为dpj=min(dpj,dpi+i*(cntj-1)+j)

cpp 复制代码
//#include<__msvc_all_public_headers.hpp>
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 5e3 + 5;
ll n;
ll a[N];
ll cost[N];
ll cnt[N];
void init()
{
	for (int i = 0; i <= n; i++)
	{
		cost[i] = 1e18;
		cnt[i] = 0;
	}
}
ll gcd(ll a, ll b)
{
	return b ? gcd(b, a % b) : a;
}
ll lowbit(ll x)
{
	return x & (-x);
}
void solve()
{
	ll m;
	cin >> n;
	init();
	for (int i = 1; i <= n; i++)
	{
		cin >> a[i];
		if (a[i] <= n)
		{//MEX最大为n,大于n的都可以随便删
			cnt[a[i]]++;
		}
	}
	int mex = 0;
	while (cnt[mex])
	{//找当前的MEX
		mex++;
	}
	cost[mex] = 0;
	for (ll i = mex; i >= 0; i--)
	{
		for (ll j = 0; j < i; j++)
		{
			cost[j] = min(cost[j], cost[i] + i * (cnt[j] - 1) + j);
		}
	}
	cout << cost[0] << endl;
}
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	int t;
	cin >> t;
	while (t--)
	{
		solve();
	}
	return 0;
}
相关推荐
塔能物联运维4 小时前
塔能两相液冷:600W/cm²极限能力,为下一代AI芯片预留充足散热余量
人工智能·算法·两相液冷
醉城夜风~5 小时前
手撕 C++ string:从零实现一个简易字符串类
开发语言·c++·算法
手写码匠5 小时前
华为云Flexus+DeepSeek征文|DeepSeek+RAG知识库实战:基于Flexus X实例与Dify构建企业级智能问答系统
人工智能·深度学习·算法·aigc
nLif5 小时前
进程管道通讯-伪终端方式
c++·windows
颜x小5 小时前
[C#]泛型类与泛型方法
开发语言·c++·c#
Lhan.zzZ5 小时前
深入理解 windeployqt:混合 C++/Qt 项目的打包指南
开发语言·c++·qt
zander2586 小时前
LeetCode 46. 全排列
算法·leetcode·深度优先
zh路西法6 小时前
【Navigation2进阶】(十二):自主探索性能优化与 RIG 算法推导与 Nav2 插件实现
c++·dijkstra·ros2·rrt·navigation2·前沿探索
星恒随风6 小时前
C++ STL 详解:set 与 multiset 的使用、区间查询和算法应用
开发语言·c++·笔记·学习·算法
Lumos1866 小时前
《ESP32 物联网全栈实战-02》ESP-IDF 工程结构
算法