Advertisement
Sourav_CSE

Krushkal Cpp

Nov 26th, 2019
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.04 KB | None | 0 0
  1. //KRUSKAL
  2. // Mohsin Riad
  3. #include<bits/stdc++.h>
  4. using namespace std;
  5. int id[100007],nodes,edges;
  6. pair<long long, pair<int ,int> > p[100007];
  7. void init()
  8. {
  9. for(int i=0;i<100007;i++)
  10. id[i]=i;
  11. return;
  12. }
  13. int find_set(int x)
  14. {
  15. if(id[x]!=x) id[x]=find_set(id[x]);
  16. return id[x];
  17. }
  18. void union_set(int x,int y)
  19. {
  20. x=find_set(x);
  21. y=find_set(y);
  22. id[x]=id[y];
  23. }
  24. long long solve()
  25. {
  26. int x, y;
  27. long long cost,min_cost=0;
  28. for(int i=0;i<edges;i++)
  29. {
  30. x=p[i].second.first;
  31. y=p[i].second.second;
  32. cost=p[i].first;
  33. if(find_set(x)!=find_set(y))
  34. {
  35. min_cost+=cost;
  36. union_set(x,y);
  37. }
  38. }
  39. return min_cost;
  40. }
  41. int main()
  42. {
  43. int x,y;
  44. long long cost;
  45. init();
  46. cin>>nodes>>edges;
  47. for(int i=0;i<edges;i++)
  48. {
  49. cin>>x>>y>>cost;
  50. p[i].second.first=x;
  51. p[i].second.second=y;
  52. p[i].first=cost;
  53. }
  54. sort(p,p+edges);
  55. cout<<solve()<<endl;
  56. return 0;
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement