题解 CF1875D【Jellyfish and Mex】
显然,除非 ,否则不会删除 的数。而 时不对答案产生贡献,因此任意时刻我们都可以忽略 中 的数。
又显然,一旦我们开始删一个数,就会先把所有与之相等的数删光。否则,设最先删光的数为 ,把所有删除 的操作提到最前面一定更优。
至此,我们自然地设 表示假设只保留所有 的数,此时删光的最小代价。注意到,我们忽略了 的数,此时 的取值范围是 ,由 的定义可知此时 。
考察首先要删光哪个数,不妨设为 ()。设 出现次数为 。显然,前 次删除时 还未被删光,此时对答案贡献为 ;最后一次删除时 已被删光,此时对答案贡献为 。删除结束后,剩余的数列满足保留了所有 的数,且 。此时,所有 的数都可以被忽略,问题转化为 。因此,得到转移方程:
时间复杂度 。
// Problem: D. Jellyfish and Mex
// Contest: Codeforces - Codeforces Round 901 (Div. 2)
// URL: https://codeforces.com/problemset/problem/1875/D
// Memory Limit: 256 MB
// Time Limit: 1000 ms
//
// Powered by CP Editor (https://cpeditor.org)
//By: OIer rui_er
#include <bits/stdc++.h>
#define rep(x, y, z) for(ll x = (y); x <= (z); ++x)
#define per(x, y, z) for(ll x = (y); x >= (z); --x)
#define debug(format...) fprintf(stderr, format)
#define fileIO(s) do {freopen(s".in", "r", stdin); freopen(s".out", "w", stdout);} while(false)
#define endl '\n'
using namespace std;
typedef long long ll;
mt19937 rnd(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now().time_since_epoch()).count());
ll randint(ll L, ll R) {
uniform_int_distribution<ll> dist(L, R);
return dist(rnd);
}
template<typename T> void chkmin(T& x, T y) {if(x > y) x = y;}
template<typename T> void chkmax(T& x, T y) {if(x < y) x = y;}
const ll N = 5e3 + 5, inf = 0x1f1f1f1f1f1f1f1fll;
ll T, n, a[N], cnt[N], dp[N];
int main() {
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
for(cin >> T; T; T--) {
cin >> n;
rep(i, 1, n) {
cin >> a[i];
if(a[i] <= n) ++cnt[a[i]];
}
ll mex = 0;
while(cnt[mex]) ++mex;
rep(i, 1, mex) dp[i] = inf;
rep(i, 1, mex) rep(j, 0, i - 1) chkmin(dp[i], dp[j] + (cnt[j] - 1) * i + j);
cout << dp[mex] << endl;
rep(i, 0, n) cnt[i] = 0;
}
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现