1
- #include < vector>
1
+ // https://onlinejudge.u-aizu.ac.jp/problems/GRL_7_A
2
+
3
+ #include < bits/stdc++.h>
4
+
2
5
3
- // Bipartite Maximum Matching
4
- // Memory: O(V + E)
5
- // NOTE: undirected, bipartite
6
6
class BipartiteMaximumMatching {
7
- int N;
8
- std::vector<std::vector<int >> adj;
9
- // Temporal
10
- std::vector<int > match;
11
- std::vector<bool > used;
7
+ size_t N;
8
+ std::vector<std::vector<size_t >> adj;
12
9
13
10
public:
14
- // O(N)
15
- BipartiteMaximumMatching (int n = 0 ): N(n), adj(n) {}
16
- // O(1)
17
- int size () {
11
+ // Time: O(N)
12
+ BipartiteMaximumMatching (size_t n = 0 )
13
+ : N(n)
14
+ , adj(n)
15
+ {
16
+ // Do nothing
17
+ }
18
+ // Time: O(1)
19
+ size_t size () const {
18
20
return N;
19
21
}
20
- // O(1)
21
- void add_edge (int u, int v) {
22
- throw_if_invalid_index (u);
23
- throw_if_invalid_index (v);
22
+ // u = [0,N), v = [0,N)
23
+ // Time: O(1)
24
+ void add_edge (size_t u, size_t v) {
25
+ if (u >= N) throw std::out_of_range (" u" );
26
+ if (v >= N) throw std::out_of_range (" v" );
24
27
adj[u].push_back (v);
25
28
adj[v].push_back (u);
26
29
}
27
- // O(V(V+E))
28
- int solve (std::vector<int >& out_match) {
29
- int ans = 0 ;
30
- match.assign (N, -1 );
31
- for (int v = 0 ; v < N; ++v) {
32
- if (match[v] != -1 ) continue ;
30
+ // Time: O( V(V+E) )
31
+ size_t solve (std::vector<size_t >& match) const {
32
+ size_t ans = 0 ;
33
+ std::vector<bool > used (N, false );
34
+ match = std::vector<size_t >(N, N);
35
+ for (size_t v = 0 ; v < N; ++v) {
36
+ if (match[v] != N) continue ;
33
37
used.assign (N, false );
34
- if (dfs (v)) ans++;
38
+ if (dfs (match, used, v)) ans++;
35
39
}
36
- out_match = std::vector<int >(match);
37
40
return ans;
38
41
}
39
42
40
43
private:
41
- void throw_if_invalid_index (int index) {
42
- if (index < 0 || index >= N) throw " index out of range" ;
43
- }
44
- bool dfs (int v) {
44
+ bool dfs (
45
+ std::vector<size_t >& match,
46
+ std::vector<bool >& used,
47
+ size_t v
48
+ ) const {
45
49
used[v] = true ;
46
- for (int u : adj[v]) {
47
- int w = match[u];
48
- if (w == - 1 || (!used[w] && dfs (w))) {
50
+ for (size_t u : adj[v]) {
51
+ size_t w = match[u];
52
+ if (w == N || (!used[w] && dfs (match, used, w))) {
49
53
match[v] = u;
50
54
match[u] = v;
51
55
return true ;
@@ -56,9 +60,9 @@ class BipartiteMaximumMatching {
56
60
};
57
61
58
62
59
- #include < iostream>
60
-
61
63
using namespace std ;
64
+ using ll = int64_t ;
65
+ using ff = long double ;
62
66
63
67
int main () {
64
68
ios_base::sync_with_stdio (false );
@@ -74,7 +78,7 @@ int main() {
74
78
matching.add_edge (x, y + X);
75
79
}
76
80
77
- vector<int > match;
81
+ vector<size_t > match;
78
82
int ans = matching.solve (match);
79
83
cout << ans << endl;
80
84
0 commit comments