MinCut.cc 1.2 KB

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