Advertisement
Araf_12

DSU + kruskal algorithm

Feb 9th, 2023 (edited)
23
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.94 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int mx=1e5+123;
  5. int parent[mx],sz[mx];
  6. void make(int v){
  7.     parent[v]=v;
  8.     sz[v]=1;
  9. }
  10.  
  11. int find(int v){
  12.     if(parent[v]==v)return parent[v];
  13.     return parent[v]=find(parent[v]);
  14. }
  15.  
  16. void Union(int a,int b){
  17.     a=find(a);
  18.     b=find(b);
  19.     if(a!=b){
  20.         if(sz[a]<sz[b])swap(a,b);
  21.         parent[b]=a;
  22.         sz[a]+=sz[b];
  23.     }
  24. }
  25.  
  26. int main()
  27. {
  28.     int n,m;cin>>n>>m;
  29.     vector<pair<int,pair<int,int>>>edges;
  30.     for(int i=0;i<m;i++){
  31.         int u,v,wt;
  32.         cin>>u>>v>>wt;
  33.         edges.push_back({wt,{u,v}});
  34.     }
  35.     sort(edges.begin(),edges.end());
  36.     for(int i=1;i<=n;i++)make(i);
  37.  
  38.     int total_cost=0;
  39.     for(auto &edge:edges){
  40.         int wt=edge.first;
  41.         int u=edge.second.first;
  42.         int v=edge.second.second;
  43.  
  44.         if(find(u)==find(v))continue;
  45.         Union(u,v);
  46.         total_cost+=wt;
  47.     }
  48.     cout<<total_cost<<endl;
  49.  
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement