From 5ac2496d1d15237ce0eec3128e357a8dcb02d119 Mon Sep 17 00:00:00 2001 From: Bruno Freitas Tissei <bft15@inf.ufpr.br> Date: Wed, 16 May 2018 14:04:53 +0200 Subject: [PATCH] Add bipartite matching Signed-off-by: Bruno Freitas Tissei <bft15@inf.ufpr.br> --- graph/bipartite_match.cpp | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 graph/bipartite_match.cpp diff --git a/graph/bipartite_match.cpp b/graph/bipartite_match.cpp new file mode 100644 index 0000000..335b4d0 --- /dev/null +++ b/graph/bipartite_match.cpp @@ -0,0 +1,38 @@ +/** + * Bipartite Matching (simplified Ford-Fulkerson) + * + * Complexity (Time): O(n + m) + * Complexity (Space): O(n + m) + */ + +vector<int> graph[MAX]; +int cont[MAX], match[MAX]; + +// Find match for x +int dfs(int x) { + if (cont[x]) + return 0; + + cont[x] = 1; + for (auto i : graph[x]) + if (match[i] == -1 || dfs(match[v])) { + match[i] = x; + return 1; + } + + return 0; +} + +// Return number of left elements in matching and fills match array with the +// match itself (match[right_i] = left_i) +int bipartite_matching(int n) { + int ans = 0; + memset(match, -1, sizeof match); + + for (int i = 0; i < n; ++i) { + memset(cont, 0, sizeof cont); + ans += dfs(i); + } + + return ans; +} -- GitLab