fork download
  1. /*
  2.   Copyright 2013,2016 Marek "p2004a" Rusinowski
  3.   Computing MST - Kruskal's algorithm
  4. */
  5. #include <cstdio>
  6. #include <vector>
  7. #include <algorithm>
  8. #include <numeric>
  9. #include <tuple>
  10.  
  11. using namespace std;
  12.  
  13. class FindUnion {
  14. vector<int> root, rank;
  15.  
  16. public:
  17. FindUnion(int n) : root(n), rank(n) {
  18. iota(root.begin(), root.end(), 0);
  19. }
  20.  
  21. int find_set(int v) {
  22. if (root[v] == v) return v;
  23. root[v] = find_set(root[v]);
  24. return root[v];
  25. }
  26.  
  27. void union_sets(int v, int u) {
  28. v = find_set(v);
  29. u = find_set(u);
  30. if (rank[v] < rank[u]) {
  31. root[v] = u;
  32. } else if (rank[v] > rank[u]) {
  33. root[u] = v;
  34. } else {
  35. root[v] = u;
  36. ++rank[v];
  37. }
  38. }
  39. };
  40.  
  41. int main() {
  42. int n, m, a, b, c;
  43. vector<tuple<int, int, int>> out;
  44. scanf("%d %d", &n, &m);
  45. FindUnion fu(n);
  46. for (int i = 0; i < m; ++i) {
  47. scanf("%d %d %d", &a, &b, &c);
  48. out.emplace_back(c, --a, --b);
  49. }
  50. sort(out.begin(), out.end());
  51. for (auto t: out) {
  52. tie(c, a, b) = t;
  53. if (fu.find_set(a) != fu.find_set(b)) {
  54. fu.union_sets(a, b);
  55. printf("%d %d\n", a + 1, b + 1);
  56. }
  57. }
  58. return 0;
  59. }
  60.  
Success #stdin #stdout 0s 3420KB
stdin
11 16
2 11 1
5 7 2
3 11 3
3 7 4
7 9 5
9 10 6
8 9 7
2 7 8
7 10 9
1 2 10
2 6 11
3 10 12
5 10 13
3 4 14
1 5 9
8 4 3
i.imgur.com/zt3O31v.png
stdout
2 11
5 7
3 11
8 4
3 7
7 9
9 10
8 9
1 5
2 6