视频加载失败

MEX:最小非负整数

210 字
1 分钟
MEX:最小非负整数

MEX 即一个数组中的最小非负整数,它满足下面三个性质:

只有在添加的数等于当前序列的mex时,mex的值才会变化。 添加操作只会使得mex变大 删除操作会使得mex的值变小。

Problem - C - Codeforces

对于一个随时插入,删除元素的数组,想高效的查询mex可使用 set 和 一个计数数组

用一个set<int> st 来记录没有出现过的数,然后直接取最小值就可以了,当然需要一个cnt来计数。

最小值用begin取得

struct Mex {
static const int N = 1e5 + 5;
int cnt[N] = {};
set<int> s;
Mex() { for (int i = 0; i < N; ++i) s.insert(i); }
void add(int x) {
if (!cnt[x]) s.erase(x);
++cnt[x];
}
void del(int x) {
if (cnt[x] == 1) s.insert(x);
if (cnt[x]) --cnt[x];
}
int get() { return *s.begin(); }
};

文章分享

如果这篇文章对你有帮助,欢迎分享给更多人!

MEX:最小非负整数
https://blog.81vm3.xyz/posts/mex/
作者
Blume
发布于
2024-10-20
许可协议
CC BY-NC-SA 4.0
Profile Image of the Author
Blume
I build interesting things.
公告
欢迎来到我的博客!
分类
标签
最新动态
站点统计
文章
38
分类
5
标签
98
总字数
23,078
运行时长
0 天
最后活动
0 天前
站点信息
构建平台
Local
博客版本
Firefly v6.16.8
文章许可
CC BY-NC-SA 4.0

当前页面没有目录

文章目录

当前页面没有目录