相关
是什么以及性质
-
:集合 中未出现的最小非负整数。
-
性质一:对于一个 个数字组成的集合 ,。
-
性质二:有多个 和有一个 ,对 的贡献是一样的。
-
性质三:对于一个 个数字组成的集合 , 中 的数字是没有用的。
给定 ,如何求 (即静态 )
- 确定 。
- 考虑 有没有出现过。
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
- 把 修改为 :删掉 ,添加 。
- 用
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;
}