学习笔记:Mex 相关

· · 算法·理论

\operatorname{mex} 相关

\operatorname{mex} 是什么以及性质

给定 S,如何求 \operatorname{mex}(S)(即静态 \operatorname{mex})

CODE

void Solve()
{
    int n; cin >> n;
    vector<bool> vis(n + 1, false);

    for (int i = 1; i <= n; i++)
    {
        int x; cin >> x;
        if (x <= n) vis[x] = true;
    }

    int mex = 0;
    while (vis[mex]) mex++;
    cout << mex << endl;
}

例:[ABC330E] Mex and Update

#include<bits/stdc++.h>
using namespace std;
/*====================*/
using lnt = long long;
/*====================*/
#define endl "\n"
/*====================*/
int n, q;
/*====================*/
const int N = 2e5 + 10;
/*====================*/
int a[N];
/*====================*/
set<int> lib;
/*====================*/
int cnt[N];
/*====================*/
void Solve()
{
    cin >> n >> q;
    for (int i = 0; i <= n; i++)
    {
        lib.insert(i);
    }
    for (int i = 1; i <= n; i++)
    {
        cin >> a[i];

        if (a[i] <= n) cnt[a[i]]++;
        lib.erase(a[i]);
    }

    for (int i = 1; i <= q; i++)
    {
        int idx, x;
        cin >> idx >> x;

        // 把 a[id] 修改为 x:
        // 先删掉 a[id]
        // 再添加一个 x
        if (a[idx] <= n)
        {
            cnt[a[idx]]--;
            if (cnt[a[idx]] == 0)
            {
                lib.insert(a[idx]);
            }   
        } 
        if (x <= n)
        {
            cnt[x]++;
            lib.erase(x);
        }
        a[idx] = x;

        cout << *lib.begin() << endl;
    }
}
/*====================*/
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr), cout.tie(nullptr);
    int t = 1; //cin >> t;
    while (t--) Solve();
    return 0;
}

例:CF2123E MEX Count

考虑枚举 \operatorname{mex}。

对于数组 a,要使 \operatorname{mex}(a) = t,至少要删掉 cnt[t] 个数,最多删除 |a| - t 个数字。也就是 [cnt[t], |a| - t] 这个区间都可以,用差分转换为区间问题即可。

CODE

#include<bits/stdc++.h>
using namespace std;
/*====================*/
using lnt = long long;
/*====================*/
#define endl "\n"
/*====================*/
const int N = 2e5 + 10;
/*====================*/
int arr[N], n, cnt[N], d[N];
/*====================*/
void Solve()
{
    cin >> n;
    for (int i = 0; i <= n + 1; i++) cnt[i] = d[i] = 0;
    for (int i = 1; i <= n; i++)
    {
        cin >> arr[i];
    }
    for (int i = 1; i <= n; i++)
    {
        cnt[ arr[i] ]++;
    }

    for (int mex = 0; mex <= n; mex++)
    {
        if (mex > 0 && !cnt[mex - 1]) 
        {
            break;  
        }   
        // min: cnt[mex]
        // max: n - mex + 1
        d[ cnt[mex] ]++;
        d[ n - mex + 1]--;
    } 

    for (int i = 0; i <= n; i++)
    {
        if (i > 0)
        {
            d[i] += d[i - 1];
        }
        cout << d[i] << " ";
    }
    cout << endl;
}
/*====================*/
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr), cout.tie(nullptr);
    int t = 1; cin >> t;
    while (t--) Solve();
    return 0;
}