Advertisement
Naimul_X

Untitled

May 31st, 2021
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. *****************This code is contributed by Naimul karim*******************
  2. #include <iostream>
  3. #include <vector>
  4. #include <utility>
  5. #include <algorithm>
  6. using namespace std;
  7. const int MAX = 1000;
  8. int id[MAX], nodes, edges;
  9. pair <long long, pair<int, int> > p[MAX];
  10.  
  11.  
  12. void init()
  13. {
  14. for(int i = 0;i < MAX;++i)
  15. id[i] = i;
  16. }
  17.  
  18. int root(int x)
  19. {
  20. while(id[x] != x) //if x is not itself parent then update its parent
  21. {
  22. id[x] = id[id[x]];
  23. x = id[x];
  24. }
  25. return x;
  26. }
  27.  
  28. void union1(int x, int y)
  29. {
  30. int p = root(x);
  31. int q = root(y);
  32. id[p] = id[q];
  33. }
  34.  
  35.  
  36. long long kruskal(pair<long long, pair<int, int> > p[])
  37. {
  38. int x, y;
  39. long long cost, minCost = 0;
  40. cout<<"MST"<<endl;
  41. for(int i = 0;i < edges;++i)
  42. {
  43. x = p[i].second.first;
  44. y = p[i].second.second;
  45. cost = p[i].first;
  46.  
  47. if(root(x) != root(y))
  48. {
  49. minCost += cost;
  50.  
  51. cout<<x<<" - "<<y<<endl;//print the edges contain in spanning tree
  52. union1(x, y);
  53. }
  54. }
  55. return minCost;
  56. }
  57.  
  58. int main()
  59. {
  60. int x, y;
  61. long long weight, cost, minCost;
  62. init();
  63.  
  64. cin >> nodes >> edges;
  65.  
  66.  
  67. for(int i = 0;i < edges;++i)
  68. {
  69.  
  70. cin >> x >> y >> weight;
  71. p[i] = make_pair(weight, make_pair(x, y));
  72. }
  73.  
  74.  
  75. sort(p, p + edges);
  76. minCost = kruskal(p);
  77. cout <<"Sum of edge weights "<< minCost << endl;
  78. return 0;
  79. }
  80.  
  81. /*
  82. 9 14
  83. 0 1 10
  84. 0 2 12
  85. 1 2 9
  86. 1 3 8
  87. 2 4 4
  88. 2 5 1
  89. 3 4 7
  90. 3 6 8
  91. 3 7 5
  92. 4 5 3
  93. 5 7 6
  94. 6 7 9
  95. 6 8 2
  96. 7 8 11
  97. */
  98.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement