MinCut.cc 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. // Adjacency matrix implementation of Stoer-Wagner min cut algorithm.
  2. // Running time:
  3. // O(|V|^3)
  4. // INPUT:
  5. // - graph, constructed using AddEdge()
  6. // OUTPUT:
  7. // - (min cut value, nodes in half of min cut)
  8. pair<int, VI> GetMinCut(VVI &weights) {
  9. int N = weights.size();
  10. VI used(N), cut, best_cut;
  11. int best_weight = -1;
  12. for (int phase = N-1; phase >= 0; phase--) {
  13. VI w = weights[0];
  14. VI added = used;
  15. int prev, last = 0;
  16. for (int i = 0; i < phase; i++) {
  17. prev = last;
  18. last = -1;
  19. for (int j = 1; j < N; j++)
  20. if (!added[j] && (last == -1 || w[j] > w[last])) last = j;
  21. if (i == phase-1) {
  22. for (int j = 0; j < N; j++) weights[prev][j] += weights[last][j];
  23. for (int j = 0; j < N; j++) weights[j][prev] = weights[prev][j];
  24. used[last] = true;
  25. cut.push_back(last);
  26. if (best_weight == -1 || w[last] < best_weight) {
  27. best_cut = cut;
  28. best_weight = w[last];
  29. }
  30. } else {
  31. for (int j = 0; j < N; j++)
  32. w[j] += weights[last][j];
  33. added[last] = true;
  34. }
  35. }
  36. }
  37. return make_pair(best_weight, best_cut);
  38. }