跳到正文

个人记录

CodeForces - 1875D

Chthohepta约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年8月2日
收录
2025年12月12日
更新
2026年11月21日
篇幅
约 3 分钟

版本

  1. v1当前

题意

给定一个包含 nn 个非负整数的数组 a1,a2,…,ana_1, a_2, \dots, a_n。

令 mm 为一个初始值为 00 的变量,Jellyfish 将进行如下操作共 nn 次:

  • 选择一个下标 ii(1≤i≤∣a∣1 \leq i \leq |a|),并从 aa 中删除 aia_i。
  • 将 MEX⁡(a)\operatorname{MEX}(a) 加到 mm 上。

现在,Jellyfish 想知道,如果每一步都最优地进行操作,mm 的最终最小可能值是多少。

思路

显然,MEX⁡(a)\operatorname{MEX}(a) 不会超过 nn。

设 dpidp_i 表示 MEX⁡(a)=i\operatorname{MEX}(a) = i 时的 mm 的值。dp0dp_0 即为最终答案。

转移:

dpi=dpj+i+max⁡(cnti−1,0)×jdp_i = dp_j + i + \max(cnt_i - 1, 0) \times j

cnticnt_i 为 ax=ia_x = i 时的 xx 的数量。

(因为题目中的操作是现删再加,所以是 i+max⁡(cnti−1,0)×ji + \max(cnt_i - 1, 0) \times j 而不是 cnti×jcnt_i \times j)。

代码

C++
#include <bits/stdc++.h>
using ll = long long;
using ld = long double;
using namespace std;

const int N = 5002;
int t, n;
int a[N];
int cnt[N];
int dp[N];

int main(){
    ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);

    cin >> t;
    while(t --){
        cin >> n;
        for(int i = 0; i <= n; i ++){
            cnt[i] = 0, dp[i] = 0;
        }
        for(int i = 1; i <= n; i ++){
            cin >> a[i];
            if(a[i] <= n){
                cnt[a[i]] ++;
                dp[a[i]] = 1e9;
            }
        }
        for(int i = n; i >= 0; i --){
            for(int j = n; j > i; j --){
                dp[i] = min(dp[i], dp[j] + i + max(cnt[i] - 1, 0) * j);
            }
        }

        cout << dp[0] << '\n';
    }
    return 0;
}


原文