a_pramanik

Minimum Spanning Tree

Jun 9th, 2016
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. #include<set>
  2. #include<list>
  3. #include<map>
  4. #include<stack>
  5. #include<string>
  6. #include<cstdio>
  7. #include<cmath>
  8. #include<queue>
  9. #include<vector>
  10. #include<cctype>
  11. #include<cstdlib>
  12. #include<cstring>
  13. #include<iterator>
  14. #include<fstream>
  15. #include<sstream>
  16. #include<numeric>
  17. #include<iostream>
  18. #include<algorithm>
  19. using namespace std;
  20.  
  21. #define pb push_back
  22. #define ll long long int
  23. #define inf 2000000000
  24. #define pi (2.0*acos(0.0))
  25. #define vsort(v) sort(v.begin(),v.end())
  26. #define ull unsigned long long int
  27. #define ff(i,a,n) for(int i=a;i<=n;i++)
  28. #define mem(a, b) memset(a, b, sizeof a)
  29.  
  30. int par[100];
  31.  
  32.  
  33. struct data
  34. {
  35. int x, y, cst;
  36. }a[100];
  37.  
  38. bool cmp(data lhs, data rhs){
  39.  
  40. return lhs.cst<rhs.cst;
  41.  
  42. }
  43.  
  44. int fin(int u){
  45.  
  46. if(par[u]==u)return u;
  47.  
  48. int s = fin(par[u]);
  49. par[u]=s;
  50. return s;
  51. }
  52.  
  53. int main()
  54.  
  55. {
  56. int n, m, i, j;
  57.  
  58. scanf("%d%d", &n, &m);
  59.  
  60. for(i=1; i<=m; i++){
  61. scanf("%d%d%d", &a[i].x, &a[i].y, &a[i].cst);
  62. }
  63.  
  64. for(i=1; i<=n; i++)par[i]=i;
  65.  
  66. sort(a+1, a+m+1, cmp);
  67.  
  68. int cost = 0;
  69. int cnt = 0;
  70. for(i=1; i<=m; i++){
  71. if(cnt>=n-1)break;
  72. int n1 = a[i].x;
  73. int n2 = a[i].y;
  74. int ccst = a[i].cst;
  75.  
  76. int f1 = fin(n1);
  77. int f2 = fin(n2);
  78.  
  79. if(f1!=f2){
  80. cost+=ccst;
  81. par[f1]=f2;
  82. cnt++;
  83. }
  84.  
  85. }
  86. printf("%d\n", cost);
  87.  
  88. return 0;
  89. }
Add Comment
Please, Sign In to add comment