-
Notifications
You must be signed in to change notification settings - Fork 2
/
Mex with update.cpp
77 lines (56 loc) · 1.49 KB
/
Mex with update.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*8<{=============~ BEGIN MEX ~===============>8*/
/*8<
@Title:
Mex with update
@Description:
This DS allows you to mantain an array of
elments, insert, and remove, and query
the MEX at any time.
@Usage:
\begin{compactitem}
\item \textbf{$Mex(mxsz)$}: Initialize
the DS, $mxsz$ must be the maximum number
of elements that the structure may have.
\item \textbf{$add(x)$}: just adds one
copy of $x$.
\item \textbf{$rmv(x)$}: just remove a copy
of $x$.
\item \textbf{$operator()$}: returns the
MEX.
\end{compactitem}
@Time:
\begin{compactitem}
\item \textbf{$Mex(mxsz)$}:
$O(\log{mxsz})$
\item \textbf{$add(x)$}: $O(\log{mxsz})$
\item \textbf{$rmv(x)$}: $O(\log{mxsz})$
\item \textbf{$operator()$}: $O(1)$
\end{compactitem}
>8*/
struct Mex {
int mx_sz;
vi hs;
set<int> st;
Mex(int _mx_sz) : mx_sz(_mx_sz), hs(mx_sz + 1) {
auto it = st.begin();
rep(i, 0, mx_sz + 1) it = st.insert(it, i);
}
void add(int x) {
if (x > mx_sz) return;
if (!hs[x]++) st.erase(x);
}
void rmv(int x) {
if (x > mx_sz) return;
if (!--hs[x]) st.emplace(x);
}
int operator()() const { return *st.begin(); }
/*
Optional, you can just create with size
len(xs) add N elements :D
*/
Mex(const vi &xs, int _mx_sz = -1)
: Mex(~_mx_sz ? _mx_sz : len(xs)) {
for (auto xi : xs) add(xi);
}
};
/*8<===============~ END MEX ~===============}>8*/