SuitNdtie

Overtree PROG1082

Mar 11th, 2019
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.19 KB | None | 0 0
  1. #include<iostream>
  2. #include<stdio.h>
  3. #include<algorithm>
  4. using namespace std;
  5.  
  6. typedef struct{
  7.     int parent;
  8.     int rank;
  9. }subset;
  10.  
  11. typedef struct{
  12.     int u;
  13.     int v;
  14.     int w;
  15. }edge;
  16.  
  17. bool mycmp(edge a,edge b){
  18.     return a.w < b.w;
  19. }
  20.  
  21. int find(int x,subset set[]){
  22.     if(set[x].parent == x){
  23.         return x;
  24.     }
  25.     return set[x].parent = find(set[x].parent,set);
  26. }
  27.  
  28. void unions(int x,int y,subset set[]){
  29.     int rootx = find(x,set);
  30.     int rooty = find(y,set);
  31.    
  32.     if(set[rootx].rank > set[rooty].rank){
  33.         set[rooty].parent = rootx;
  34.     }
  35.     else if(set[rootx].rank < set[rooty].rank){
  36.         set[rootx].parent = rooty;
  37.     }else{
  38.         set[rootx].parent = rooty;
  39.         set[rooty].rank++;
  40.     }
  41. }
  42.  
  43. int main()
  44. {
  45.     int v,e;
  46. //  cin>>v>>e;
  47.     scanf("%d%d",&v,&e);
  48.     subset set[v+1];
  49.     for(int i=0;i<=v;i++){
  50.         set[i].parent = i;
  51.         set[i].rank = 0;
  52.     }
  53.     edge alledge[e];
  54.     for(int i=0;i<e;i++){
  55.         int u,v,w;
  56.     //  cin>>u>>v>>w;
  57.         scanf("%d%d%d",&u,&v,&w);
  58.         alledge[i] = {u,v,w};
  59.     }
  60.     sort(alledge,alledge+e,mycmp);
  61.     for(int i=0;i<e;i++){
  62.         int x = alledge[i].u;
  63.         int y = alledge[i].v;
  64.         if(find(x,set) != find(y,set)){ // not cycle
  65.         //  cout<<x<<" "<<y<<endl;
  66.             printf("%d %d\n",x,y);
  67.             unions(x,y,set);
  68.         }
  69.     }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment