Advertisement
Korotkodul

СНМ

Mar 27th, 2022 (edited)
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.81 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3. #include <vector>
  4. #include <queue>
  5. #include <algorithm>
  6. #include <string>
  7. #include <stack>
  8. #include <set>
  9. #include <map>
  10. #define pii pair <int,int>
  11. #define vec vector
  12. using namespace std;
  13. using ll = long long;
  14. using ld = long double;
  15. using db = double;
  16. void cv(vector <int> &v){
  17.     for (auto x: v) cout<<x<<' ';
  18.     cout<<"\n";
  19. }
  20.  
  21. void cvl(vector <ll> &v){
  22.     for (auto x: v) cout<<x<<' ';
  23.     cout<<"\n";
  24. }
  25.  
  26.  
  27. void cvv(vector <vector <int> > &v){
  28.     for (auto x: v) cv(x);
  29.     cout<<"\n";
  30. }
  31.  
  32. void cvb(vector <bool> v){
  33.     for (bool x: v) cout<<x<<' ';
  34.     cout<<"\n";
  35. }
  36.  
  37. void cvs(vector <string>  v){
  38.     for (auto a: v){
  39.         cout<<a<<"\n";
  40.     }
  41. }
  42.  
  43.  
  44. //vol - volume, wei - weight
  45.  
  46. vector <int> par, vol, wei;
  47.  
  48.  
  49. struct ed{
  50.     int fr, to, w;
  51. };
  52.  
  53. vector <ed> G;
  54.  
  55. bool cmp(ed a, ed b){
  56.     return a.w < b.w;
  57. }
  58.  
  59. //get_leader
  60. int lead(int v){
  61.     if (par[v] == -1){
  62.         return v;
  63.     }
  64.     else {
  65.         int fth = lead(par[v]);//father
  66.         par[v] = fth;
  67.         return fth;
  68.     }
  69. }
  70.  
  71.  
  72. void unite(ed x){
  73.     int a = x.fr, b = x.to , w = x.w;
  74.     int lda = lead(a), ldb = lead(b);
  75.     if (lda == ldb){
  76.         return;
  77.     }
  78.     if (vol[lda] < vol[ldb]){
  79.         swap(lda,ldb);
  80.     }
  81.     par[ldb] = lda;
  82.     vol[lda] += vol[ldb];
  83.     wei[lda] += wei[ldb] + w;
  84. }
  85.  
  86. int main()
  87. {
  88.     ios::sync_with_stdio(0);
  89.     cin.tie(0);
  90.     cout.tie(0);
  91.     int n,m;
  92.     cin>>n>>m;
  93.     par.assign(n,-1);
  94.     vol.assign(n, 1);
  95.     wei.assign(n, 0);
  96.     G.resize(m);
  97.     for (int i = 0; i < m;++i){
  98.         int a,b,c;
  99.         cin>>a>>b>>c;
  100.         a--;
  101.         b--;
  102.         ed x = {a,b,c};
  103.         G[i] = x;
  104.     }
  105.     sort(G.begin(), G.end(), cmp);
  106.     for (int i = 0; i < m;++i){
  107.         unite(G[i]);
  108.     }
  109.     int god = lead(0);
  110.     cout<<wei[god];
  111. }
  112.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement