Advertisement
aakib_alam

Kruskal_Algorithm

Aug 15th, 2022
641
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.52 KB | Source Code | 0 0
  1. /*
  2.                                   Kruskal Algorithm
  3.                              Time Complexity : O(mlogn)
  4.         Spanning Tree : Tree formed from a graph after removing some of the edges.
  5.         Minimum Spanning Tree : Spanning tree whose sum/product of edge weights is minimum.
  6.         Maximum Spanning Tree : Spanning tree whose sum/product of edge weights is maximum.
  7.     To obtain maximum spanning tree, multiply all the edge weights with -1 and apply any mst algorithm.
  8. */
  9.  
  10. #include <bits/stdc++.h>
  11. using namespace std;
  12.  
  13. const int MAXN = 100005;
  14. vector<int> id(MAXN), rnk(MAXN);
  15. vector<vector<int>> edges;
  16.  
  17. int find_set(int x)
  18. {
  19.     if (id[x] == x)
  20.         return x;
  21.     return id[x] = find_set(id[x]);
  22. }
  23.  
  24. void union_set(int x, int y)
  25. {
  26.     x = find_set(x);
  27.     y = find_set(y);
  28.     if (x == y)
  29.         return;
  30.     if (rnk[x] < rnk[y])
  31.         swap(x, y);
  32.     id[y] = x;
  33.     rnk[x] += rnk[y];
  34. }
  35.  
  36. void kruskal(int n)
  37. {
  38.     for (int i = 0; i <= n; i++)
  39.         id[i] = i, rnk[i] = 1;
  40.  
  41.     int ret = 0, x, y;
  42.     for (auto edge : edges)
  43.     {
  44.         x = find_set(edge[1]);
  45.         y = find_set(edge[2]);
  46.         if (x != y)
  47.         {
  48.             ret += edge[0];
  49.             union_set(x, y);
  50.         }
  51.     }
  52.     // cout<<ret<<"\n";
  53. }
  54.  
  55. int main()
  56. {
  57.     int n, m;
  58.     cin >> n >> m;
  59.     for (int i = 0; i < m; i++)
  60.     {
  61.         int u, v, w;
  62.         cin >> u >> v >> w;
  63.         edges.push_back({w, u, v});
  64.     }
  65.     sort(edges.begin(), edges.end());
  66.  
  67.     kruskal(n);
  68.  
  69.     return 0;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement