-
Notifications
You must be signed in to change notification settings - Fork 0
/
hopcroft_karp.cpp
89 lines (70 loc) · 1.74 KB
/
hopcroft_karp.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
78
79
80
81
82
83
84
85
86
87
88
89
// BOJ 2188 축사 배정
#include <bits/stdc++.h>
#define sz size()
#define bk back()
#define fi first
#define se second
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
bool dfs(int cur, vector<int> &a, vector<int> &b, vector<int> &lvl, vector<vector<int>> &graph) {
for (int nxt : graph[cur]) {
if (lvl[b[nxt]] == lvl[cur] + 1 && (b[nxt] == 0 || dfs(b[nxt], a, b, lvl, graph))) {
a[cur] = nxt;
b[nxt] = cur;
return true;
}
}
lvl[cur] = INT_MAX;
return false;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n, m;
cin >> n >> m;
vector<vector<int>> graph(n + 1);
for (int i = 1; i <= n; i++) {
int k;
cin >> k;
while (k--) {
int x;
cin >> x;
graph[i].push_back(x);
}
}
vector<int> a(n + 1);
vector<int> b(m + 1);
vector<int> lvl(n + 1);
int ans = 0;
while (1) {
lvl[0] = INT_MAX;
deque<int> dq;
for (int i = 1; i <= n; i++) {
if (a[i] == 0) {
lvl[i] = 0;
dq.push_back(i);
} else
lvl[i] = INT_MAX;
}
while (dq.sz) {
int cur = dq.front();
dq.pop_front();
for (int nxt : graph[cur]) {
if (lvl[b[nxt]] == INT_MAX) {
lvl[b[nxt]] = lvl[cur] + 1;
dq.push_back(b[nxt]);
}
}
}
int flow = 0;
for (int i = 1; i <= n; i++)
if (!a[i] && dfs(i, a, b, lvl, graph))
flow++;
if (flow == 0)
break;
ans += flow;
}
cout << ans;
}