学习笔记:Mex 相关
\operatorname{mex} 相关
\operatorname{mex} 是什么以及性质
-
-
性质一:对于一个
n 个数字组成的集合S ,0 \le \operatorname{mex}(S) \le n 。 -
性质二:有多个
x 和有一个x ,对\operatorname{mex} 的贡献是一样的。 -
性质三:对于一个
n 个数字组成的集合S ,S 中\ge n 的数字是没有用的。
给定 S ,如何求 \operatorname{mex}(S) (即静态 \operatorname{mex} )
- 确定
|S| 。 - 考虑
0 \sim |S| 有没有出现过。
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
- 把
a_i 修改为x :删掉a_i ,添加x 。 - 用
std::set保存没有出现过的数字,用桶辅助删除元素的过程。
#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
考虑枚举
对于数组 cnt[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;
}