nq1s788

Краскал мин остов с выводом

Nov 9th, 2025
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.38 KB | None | 0 0
  1. #include <iostream>
  2. #include <set>
  3. #include <vector>
  4. #include <deque>
  5. #include <map>
  6. #include <cmath>
  7. #include <random>
  8. #include <algorithm>
  9.  
  10. #define se second
  11. #define fi first
  12. #define mp make_pair
  13. #define pb push_back
  14.  
  15. typedef long long ll;
  16. typedef long double ld;
  17.  
  18. using namespace std;
  19.  
  20. vector<int> p, w;
  21.  
  22. int get_root(int x) {
  23.     if (p[x] == x) return x;
  24.     return p[x] = get_root(p[x]);
  25. }
  26.  
  27. bool is_equal(int x, int y) {
  28.     return get_root(x) == get_root(y);
  29. }
  30.  
  31. void unite(int x, int y) {
  32.     x = get_root(x);
  33.     y = get_root(y);
  34.     if (w[x] > w[y]) swap(x, y);
  35.     p[x] = y;
  36.     w[y] += w[x];
  37. }
  38.  
  39. int main() {
  40.     int n, m;
  41.     cin >> n >> m;
  42.     vector<pair<int, pair<int, int>>> a; ///{вес ребра, {x, y}}
  43.     for (int i = 0; i < m; i++) {
  44.         int x, y, w;
  45.         cin >> x >> y >> w;
  46.         x--, y--;
  47.         a.push_back({w, {x, y}});
  48.     }
  49.     sort(a.begin(), a.end());
  50.     vector<pair<int, int>> ostov;
  51.     int answ = 0;
  52.     p.resize(n);
  53.     for (int i = 0; i < n; i++) {
  54.         p[i] = i;
  55.     }
  56.     w.assign(n, 1);
  57.     for (auto e : a) {
  58.         if (!is_equal(e.se.fi, e.se.se)) {
  59.             answ += e.fi;
  60.             ostov.push_back(e.se);
  61.             unite(e.se.fi, e.se.se);
  62.         }
  63.     }
  64.     cout << answ << '\n';
  65.     for (auto e : ostov) {
  66.         cout << e.fi + 1 << ' ' << e.se + 1 << '\n';
  67.     }
  68.     return 0;
  69. }
Advertisement
Add Comment
Please, Sign In to add comment