Advertisement
pasholnahuy

Остов с наименьшим максимальным ребром

May 28th, 2023
1,055
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.64 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <cmath>
  5. #include <iomanip>
  6. #include <tuple>
  7. #include <map>
  8.  
  9. using namespace std;
  10.  
  11. class DSU {
  12. public:
  13.     vector<int> parent;
  14.     vector<int> height;
  15.  
  16.     DSU(int n) {
  17.         parent.resize(n);
  18.         for (int i = 0; i < n; ++i) {
  19.             parent[i] = i;
  20.         }
  21.         height.assign(n, 0);
  22.     }
  23.  
  24.     int findRoot(int v) {
  25.         if (v == parent[v]) {
  26.             return v;
  27.         }
  28.         int ans = findRoot(parent[v]);
  29.         parent[v] = ans;
  30.         return ans;
  31.     }
  32.  
  33.     void Union(int v1, int v2) {
  34.         if (height[v1] >= height[v2]) {
  35.             parent[v2] = v1;
  36.             height[v1] = max(height[v1], height[v2] + 1);
  37.         } else {
  38.             parent[v1] = v2;
  39.             height[v2] = max(height[v2], height[v1] + 1);
  40.         }
  41.     }
  42.  
  43.  
  44. };
  45.  
  46. int main() {
  47.     int n, m;
  48.     cin >> n >> m;
  49.     vector<pair<double, pair<int, int>>> edges;
  50.     map<pair<int, int>, int> edges_num;
  51.     for (int i = 0; i < m; ++i) {
  52.         int x, y, w;
  53.         cin >> x >> y >> w;
  54.         edges.push_back({w, {--x, --y}});
  55.         if (!edges_num.contains({x, y})){
  56.             edges_num[{x, y}] = i;
  57.         }
  58.     }
  59.     DSU graph(n);
  60.     sort(edges.begin(), edges.end());
  61.     double ans = 0;
  62.     for (auto [weight, coords]: edges) {
  63.         if (graph.findRoot(coords.first) != graph.findRoot(coords.second)){
  64.             graph.Union(graph.findRoot(coords.first), graph.findRoot(coords.second));
  65.             ans += weight;
  66.             cout << edges_num[coords] + 1 << " ";
  67.         }
  68.     }
  69. //    cout << '\n' << ans;
  70.     return 0;
  71. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement