SuitNdtie

Connect the Graph

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