-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathHungarian.cpp
More file actions
45 lines (45 loc) · 946 Bytes
/
Hungarian.cpp
File metadata and controls
45 lines (45 loc) · 946 Bytes
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
// Hungarian Algorithm (assignment problem)
int k;
vector<int>g[505];
int match[505];
int vis[505];
vector<int>v;
bool dfs(int x) {
for (auto i : g[x]) {
if (!match[i]) {
match[i] = x;
return 1;
}
else if (!vis[match[i]]) {
vis[match[i]] = 1;
v.push_back(match[i]);
if (dfs(match[i])) {
match[i] = x;
return 1;
}
}
}
return 0;
}
void solve() {
// Hungarian Matching
memset(match, 0 ,sizeof(match));
int n, m;
cin >> n >> m;
for (int i = 0 ; i < m ; i++) {
int a, b;
cin >> a >> b;
g[a].push_back(b);
}
int ans = 0;
for (int i = 1 ; i <= n ; i++) {
if (dfs(i)) {
ans++;
}
while (v.size()) {
vis[v.back()] = 0;
v.pop_back();
}
}
cout << ans << '\n'; // match number
}