MaxBipartiteMatching.cc 931 B

12345678910111213141516171819202122232425262728293031
  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. bool FindMatch(int i, const VVI &w, VI &mr, VI &mc, VI &seen) {
  10. for (int j = 0; j < w[i].size(); j++) {
  11. if (w[i][j] && !seen[j]) {
  12. seen[j] = true;
  13. if (mc[j] < 0 || FindMatch(mc[j], w, mr, mc, seen)) {
  14. mr[i] = j;
  15. mc[j] = i;
  16. return true;
  17. }
  18. }
  19. }
  20. return false;
  21. }
  22. int BipartiteMatching(const VVI &w, VI &mr, VI &mc) {
  23. mr = VI(w.size(), -1);
  24. mc = VI(w[0].size(), -1);
  25. int ct = 0;
  26. for (int i = 0; i < w.size(); i++) {
  27. VI seen(w[0].size());
  28. if (FindMatch(i, w, mr, mc, seen)) ct++;
  29. }
  30. return ct;
  31. }