Advertisement
urmisaha

Krushkal Implementation

Oct 21st, 2019
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.96 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. int g_nodes, g_edges, f, t, w;
  6. vector<int> parent(3001, -1);
  7.  
  8. int root(int x){
  9.     if(x == parent[x])
  10.     return x;
  11. return root(parent[x]);
  12. }
  13.  
  14. void unio(int x, int y){
  15.     int p = root(x);
  16.     int q = root(y);
  17.     parent[p] = parent[q];
  18. }
  19.  
  20. void kruskals(pair<int, pair<int, int> > g[]) {
  21.     int cost = 0;
  22.     sort(g, g+g_edges);
  23.     for(int i=1; i<=g_nodes; ++i)
  24.         parent[i] = i;
  25.     for(int i=0; i<g_edges; ++i){
  26.         int x = g[i].second.first;
  27.         int y = g[i].second.second;
  28.         if(root(x) != root(y)){
  29.             unio(x, y);
  30.             cost += g[i].first;
  31.         }
  32.     }
  33.     cout<<cost<<endl;
  34. }
  35.  
  36. int main()
  37. {
  38.     ios_base::sync_with_stdio(false);
  39.     cin>>g_nodes>>g_edges;
  40.     pair<int, pair<int, int> > g[g_edges];
  41.     for (int i = 0; i < g_edges; i++) {
  42.         cin>>f>>t>>w;
  43.         g[i] = make_pair(w, make_pair(f, t));
  44.     }
  45.     kruskals(g);
  46.     return 0;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement