al__nasim

kruskal

Dec 5th, 2016
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. //kruskal algorithm for MST
  2. //time complexity O(m log m)
  3. #include<bits/stdc++.h>
  4. #define MAXM 100
  5. #define pb push_back
  6. using namespace std;
  7.  
  8. struct edge
  9. {
  10. int u,v,w;
  11. //there is an edge between u and v of weight w
  12. };
  13.  
  14. bool operator <(edge A, edge B)
  15. {
  16. return A.w <B.w;
  17. //short edge according to weights
  18. }
  19. //edge list enough, no need for adjacency list
  20. vector < edge > e;
  21. //array to keep track of parents for union find.
  22. int p[MAXM];
  23.  
  24. int find(int x)
  25. {
  26. return (p[x]==x) ? x : find(p[x]);
  27. //if(p[x] == x) return x;
  28. //return p[x] = find(p[x]);
  29. }
  30.  
  31. int kruskal(int n)
  32. {
  33. sort(e.begin(), e.end());
  34. //if we do not store size in a variable before the loop,then it will get TLE
  35. //int sz = e.size();
  36. int ans = 0;
  37. for(int i=0; i<e.size(); i++)
  38. {
  39. if(find(e[i].u) != find(e[i].v))
  40. {
  41. //union
  42. p[e[i].u] = p[e[i].v];
  43. ans += e[i].w;
  44. }
  45. }
  46. return ans;
  47. }
  48.  
  49. int main()
  50. {
  51. int V,E;
  52. cout <<"Enter vertex and edges :";
  53. cin >> V >>E;//input vertex/node and edge
  54. cout <<"Enter per vertex to vertex and their weight:"<<endl;
  55. for(int i=1; i<=E; i++)
  56. {
  57. int u,v,w;
  58. cin >>u >>v >>w;//vertex to vertex and their weight
  59. edge get;
  60. get.u = u;
  61. get.v = v;
  62. get.w = w;
  63. e.pb(get);
  64. }
  65. cout<<"MST is" << kruskal(V) <<endl;
  66. return 0;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment