diff --git a/graph/bipartite_match.cpp b/graph/bipartite_match.cpp new file mode 100644 index 0000000000000000000000000000000000000000..335b4d051c42a043cdacd24988b4dd28a77bd14a --- /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; +}