ke_timofeeva7

Алгоритм Краскала

Jun 25th, 2021
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.74 KB | None | 0 0
  1.  
  2. #include <iostream>
  3. #include <string>
  4. #include <sstream>
  5. #include <vector>
  6. #include <cmath>
  7. #include <algorithm>
  8. #include <memory.h>
  9. #include <stdio.h>
  10. #include <stack>
  11. #include <deque>
  12. #include <queue>
  13. #include <set>
  14. #include <iterator>
  15. #include <map>
  16. #include <iomanip>
  17. #include <unordered_set>
  18. #include <array>
  19. #define int long long
  20. #define pb push_back
  21. #define fir first
  22. #define sec second
  23. #define double long double
  24. #define endl "\n"
  25. #define un unsigned
  26. #define INF 1000000000009
  27. #define EPS 0.000000000001
  28. #define pii pair<int, int>
  29. #define all(v) v.begin(), v.end()
  30. using namespace std;
  31.  
  32. vector <int> p(100005);
  33.  
  34. int rk[100005];
  35.  
  36. void make_set(int v)
  37. {
  38.     p[v] = v;
  39.     rk[v] = 0;
  40. }
  41.  
  42. int dsu_get(int v)
  43. {
  44.     if (v == p[v])
  45.     {
  46.         return v;
  47.     }
  48.  
  49.     return p[v] = dsu_get(p[v]);
  50. }
  51.  
  52. void union_set(int a, int b)
  53. {
  54.     a = dsu_get(a);
  55.     b = dsu_get(b);
  56.  
  57.     if (a == b)
  58.     {
  59.         return;
  60.     }
  61.  
  62.     if (rk[a] > rk[b])
  63.     {
  64.         swap(a, b);
  65.     }
  66.  
  67.     if (rk[a] == rk[b])
  68.     {
  69.         rk[b]++;
  70.     }
  71.  
  72.     p[a] = b;
  73.  
  74.     return;
  75. }
  76.  
  77. signed main()
  78. {
  79.     ios_base::sync_with_stdio(false);
  80.     cin.tie(0);
  81.     cout.tie(0);
  82.  
  83.     int n, m, q;
  84.     cin >> n >> m;
  85.  
  86.     vector <pair <int, pii>> gr;
  87.  
  88.     for (int i = 0; i < m; i++)
  89.     {
  90.         int a, b, w;
  91.         cin >> a >> b >> w;
  92.  
  93.         gr.pb({ w, { a, b } });
  94.     }
  95.  
  96.     int cost = 0;
  97.  
  98.     vector<pii> res;
  99.  
  100.     sort(all(gr));
  101.  
  102.     for (int i = 0; i < n; i++)
  103.     {
  104.         make_set(i);
  105.     }
  106.  
  107.     for (int i = 0; i < m; i++)
  108.     {
  109.         int a = gr[i].second.first;
  110.         int b = gr[i].second.second;
  111.         int l = gr[i].first;
  112.  
  113.         if (dsu_get(a) != dsu_get(b))
  114.         {
  115.             cost += l;
  116.             res.push_back(gr[i].second);
  117.             union_set(a, b);
  118.         }
  119.     }
  120.  
  121.     if (res.size() == n - 1)
  122.     {
  123.         cout << cost;
  124.     }
  125.     else
  126.     {
  127.         cout << "NON-CONNECTED";
  128.     }
  129.  
  130.     return 0;
  131. }
  132.  
Advertisement
Add Comment
Please, Sign In to add comment