Saleh127

UVA 11631 / MST using DSU

Sep 22nd, 2021
279
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define ll long long
  4. #define test int tt; cin>>tt; for(int cs=1;cs<=tt;cs++)
  5.  
  6. vector<ll>parent,rankk;
  7.  
  8. vector<pair<ll,pair<ll,ll>>>edge;
  9.  
  10. void make_set(ll n)
  11. {
  12. for(ll i=0; i<n; i++)
  13. {
  14. parent[i] = i;
  15. rankk[i] = 0;
  16. }
  17. }
  18.  
  19. int find_set(ll v)
  20. {
  21. if (v == parent[v])
  22. {
  23. return v;
  24. }
  25. return parent[v] = find_set(parent[v]);
  26. }
  27.  
  28. void union_sets(ll a, ll b)
  29. {
  30. a = find_set(a);
  31. b = find_set(b);
  32.  
  33. if (a != b)
  34. {
  35. if(rand()%2)
  36. {
  37. swap(a,b);
  38. }
  39. parent[b]=a;
  40.  
  41. /* else use this
  42. if (rankk[a] < rankk[b])
  43. {
  44. swap(a, b);
  45. }
  46.  
  47. parent[b] = a;
  48.  
  49. if (rankk[a] == rankk[b])
  50. {
  51. rankk[a]++;
  52. }
  53. */
  54. }
  55. }
  56.  
  57.  
  58. int main()
  59. {
  60. ios_base::sync_with_stdio(0);
  61. cin.tie(0);
  62. cout.tie(0);
  63.  
  64. ll n,m,i,j,k,l,c,d,e,f;
  65.  
  66. while(cin>>n>>m && (n+m)!=0)
  67. {
  68. l=c=0;
  69. edge.clear();
  70.  
  71. parent.resize(n);
  72. rankk.resize(n);
  73.  
  74. make_set(n);
  75.  
  76. for(i=0; i<m; i++)
  77. {
  78. cin>>d>>e>>f;
  79. l+=f;
  80. edge.push_back({f,{d,e}});
  81. }
  82.  
  83. sort(edge.begin(),edge.end());
  84.  
  85.  
  86. for(auto dd:edge)
  87. {
  88. if(find_set(dd.second.second)!=find_set(dd.second.first))
  89. {
  90. c+=dd.first;
  91. union_sets(dd.second.first,dd.second.second);
  92. }
  93. }
  94.  
  95. cout<<l-c<<endl;
  96. }
  97.  
  98.  
  99.  
  100.  
  101. return 0;
  102. }
  103.  
Advertisement
Add Comment
Please, Sign In to add comment