题解 CF1875D【Jellyfish and Mex】

显然,除非 mexa=0,否则不会删除 >mexa 的数。而 mexa=0 时不对答案产生贡献,因此任意时刻我们都可以忽略 a>mexa 的数。

又显然,一旦我们开始删一个数,就会先把所有与之相等的数删光。否则,设最先删光的数为 x,把所有删除 x 的操作提到最前面一定更优。

至此,我们自然地设 fi 表示假设只保留所有 <i 的数,此时删光的最小代价。注意到,我们忽略了 >mexa 的数,此时 i 的取值范围是 [0,mexa],由 mex 的定义可知此时 mexa=i

考察首先要删光哪个数,不妨设为 jj<i)。设 j 出现次数为 cnt(j)。显然,前 cnt(j)1 次删除时 j 还未被删光,此时对答案贡献为 i;最后一次删除时 j 已被删光,此时对答案贡献为 j。删除结束后,剩余的数列满足保留了所有 <j 的数,且 mexa=j。此时,所有 [j+1,i1] 的数都可以被忽略,问题转化为 fj。因此,得到转移方程:

fi={0,i=0minj<i{fj+(cnt(j)1)×i+j},i>0

时间复杂度 O(n2)

// 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;
}
posted @   rui_er  阅读(176)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示