Derga

Untitled

May 29th, 2024
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <vector>
  4.  
  5. using namespace std;
  6.  
  7. struct Cable {
  8. int u;
  9. int v;
  10. int cost;
  11. int idx;
  12. };
  13.  
  14. struct Dsu {
  15. Dsu(int size) : p(size, -1) {}
  16.  
  17. int GetParent(int u) {
  18. if (p[u] < 0) return u;
  19. return p[u] = GetParent(p[u]);
  20. }
  21.  
  22. void Union(int u, int v) {
  23. if (GetParent(u) == GetParent(v)) return;
  24.  
  25. int pu = GetParent(u);
  26. int pv = GetParent(v);
  27. if (p[pu] > p[pv])
  28. swap(pu, pv);
  29. p[pu] += p[pv];
  30. p[pv] = pu;
  31. }
  32.  
  33. vector<int> p;
  34. };
  35.  
  36. int main() {
  37. int towns_count, cables_count;
  38. cin >> towns_count >> cables_count;
  39. vector <Cable> cables(cables_count);
  40. int i = 1;
  41. for (auto& [u, v, cost, idx] : cables) {
  42. cin >> u >> v >> cost;
  43. idx = i;
  44. ++i;
  45. }
  46. sort(begin(cables), end(cables), [](const Cable& lhs, const Cable& rhs) {
  47. return tie(lhs.cost, lhs.u, lhs.v, lhs.idx) < tie(rhs.cost, rhs.u, rhs.v, rhs.idx);
  48. });
  49.  
  50. Dsu dsu(1+ towns_count);
  51. vector<int> required_cables_idxs;
  52. int total_cost = 0;
  53. int required_cabels_count = 0;
  54. for (const auto[u, v, cost, idx] : cables) {
  55. if (dsu.GetParent(u) != dsu.GetParent(v)) {
  56. dsu.Union(u, v);
  57. total_cost += cost;
  58. ++required_cabels_count;
  59. required_cables_idxs.push_back(idx);
  60. }
  61. }
  62.  
  63. sort(begin(required_cables_idxs), end(required_cables_idxs));
  64.  
  65. cout << total_cost << ' ' << required_cabels_count << '\n';
  66. for (int idx : required_cables_idxs) cout << idx << ' ';
  67.  
  68. return 0;
  69. }
  70.  
  71. /*
  72. test1
  73. 2 2
  74. 1 2 3
  75. 1 2 4
  76.  
  77. 3 1
  78. 1
  79.  
  80. test2
  81. 3 3
  82. 1 2 5
  83. 1 3 10
  84. 3 2 4
  85.  
  86. 14 2
  87. 2 3
  88. */
Advertisement
Add Comment
Please, Sign In to add comment