Advertisement
Oppenheimer

MST (Kruskal with DSU , rank and path comp)

Aug 19th, 2022 (edited)
32
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.29 KB | None | 0 0
  1.  
  2.  
  3. bool cmp(vector<int>&a,vector<int>&b){
  4.     return a[2]<b[2];
  5. }
  6.  
  7.  
  8.    
  9.     vector<int> parent, rank;
  10.    
  11.     void make_set(int x){
  12.         parent[x] =x ;
  13.         rank[x] = 0;
  14.     }
  15.    
  16.     int find_set(int x){
  17.         if(x == parent[x])return x;
  18.         else parent[x] = find_set(parent[x]);
  19.        
  20.     }
  21.    
  22.     void union_set(int a, int b){
  23.         a = find_set(a);
  24.         b = find_set(b);
  25.        
  26.         if(a != b){
  27.             if(rank[a] < rank[b]){
  28.                 parent[a] = b;
  29.             }
  30.             else if(rank[a]>rank[b]){
  31.                 parent[b]=a;
  32.                
  33.             }
  34.             else{
  35.                 parent[b] =a;
  36.                 rank[a]++;
  37.             }
  38.         }
  39.     }
  40.    
  41.    
  42.    
  43.     int spanningTree(int V, vector<vector<int>> adj[])
  44.     {
  45.         int cost=0;
  46.         parent.resize(V+1);
  47.         rank.resize(V);
  48.         for(int i=0;i<V;i++)make_set(i);
  49.         vector<vector<int>> edges;
  50.         for(int i=0;i<V;i++){
  51.             for(auto it:adj[i]){
  52.                 edges.push_back({i,it[0],it[1]});
  53.                
  54.             }
  55.         }
  56.        
  57.         sort(edges.begin(),edges.end(),cmp);
  58.        
  59.         for(vector<int> e : edges){
  60.             if(find_set(e[0])!=find_set(e[1])){
  61.                 cost+=e[2];
  62.                 union_set(e[0],e[1]);
  63.             }
  64.         }
  65.         return cost;
  66.     }
  67. };
  68.  
  69.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement