MaxBipartiteMatching.cc 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. // This code performs maximum bipartite matching.
  2. //
  3. // Running time: O(|E| |V|) -- often much faster in practice
  4. //
  5. // INPUT: w[i][j] = edge between row node i and column node j
  6. // OUTPUT: mr[i] = assignment for row node i, -1 if unassigned
  7. // mc[j] = assignment for column node j, -1 if unassigned
  8. // function returns number of matches made
  9. #include <vector>
  10. using namespace std;
  11. typedef vector<int> VI;
  12. typedef vector<VI> VVI;
  13. bool FindMatch(int i, const VVI &w, VI &mr, VI &mc, VI &seen) {
  14. for (int j = 0; j < w[i].size(); j++) {
  15. if (w[i][j] && !seen[j]) {
  16. seen[j] = true;
  17. if (mc[j] < 0 || FindMatch(mc[j], w, mr, mc, seen)) {
  18. mr[i] = j;
  19. mc[j] = i;
  20. return true;
  21. }
  22. }
  23. }
  24. return false;
  25. }
  26. int BipartiteMatching(const VVI &w, VI &mr, VI &mc) {
  27. mr = VI(w.size(), -1);
  28. mc = VI(w[0].size(), -1);
  29. int ct = 0;
  30. for (int i = 0; i < w.size(); i++) {
  31. VI seen(w[0].size());
  32. if (FindMatch(i, w, mr, mc, seen)) ct++;
  33. }
  34. return ct;
  35. }