Advertisement
istinishat

kruskal_own_version

Mar 2nd, 2017
259
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include<iostream>
  2. #include<cstdio>
  3. #include<vector>
  4. #include<algorithm>
  5. using namespace std;
  6.  
  7. #define si(n) scanf("%d",&n)
  8. #define f first
  9. #define s second
  10. #define mp(a,b) make_pair(a,b)
  11. #define MAX 10004
  12.  
  13. vector<int>graph[MAX];
  14. vector<pair<int,pair<int,int> > >edge;
  15. int n,m,parent[MAX],rnk[MAX];
  16.  
  17. void make_set (int v) {
  18.     parent[v] = v;
  19.     rnk[v] = 0;
  20. }
  21.  
  22. int find_set (int v) {
  23.     if (v == parent[v])
  24.         return v;
  25.     return parent[v] = find_set (parent[v]);
  26. }
  27.  
  28. void union_sets (int a, int b) {
  29.     a = find_set (a);
  30.     b = find_set (b);
  31.     if (a != b) {
  32.         if (rnk[a] < rnk[b])
  33.             swap (a, b);
  34.         parent[b] = a;
  35.         if (rnk[a] == rnk[b])
  36.             ++rnk[a];
  37.     }
  38. }
  39.  
  40. int main()
  41. {
  42.     int i,j;
  43.     si(n);si(m);
  44.     for(i=0;i<m;i++){
  45.         int u,v,w;
  46.         si(u);si(v);si(w);
  47.         graph[u].push_back(v);
  48.         graph[v].push_back(u);
  49.         edge.push_back(mp(w,mp(u,v)));
  50.     }
  51.     sort(edge.begin(),edge.end());
  52.     long long MST=0;
  53.    
  54.     for(i=1;i<=n;i++)
  55.         make_set(i);
  56.        
  57.     for(i=0;i<m;i++){
  58.         int u=edge[i].s.f,v=edge[i].s.s,w=edge[i].f;
  59.         if(find_set(u)==find_set(v))
  60.             continue;
  61.         MST+=w;
  62.         union_sets(u,v);
  63.     }
  64.  
  65.     cout<<MST<<endl;
  66.     return 0;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement