Advertisement
remember_Me

Untitled

Aug 7th, 2020
494
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.23 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define all(x)                x.begin(),x.end()
  3. #define pb                    push_back
  4. #define IOfast                ios_base::sync_with_stdio(false); cin.tie(NULL);
  5. using namespace std;
  6.  
  7. //dsu struct 1 is the starting
  8.  
  9. struct dsu_struct
  10. {
  11.   vector<int> par; //parent of node
  12.   int total_comp;  //total component
  13.  
  14.   void init(int n)
  15.   { //index 1 is the starting
  16.     total_comp = n;
  17.     par.resize(n+1);
  18.     for(int i=1;i<=n;i++) par[i] = i;
  19.   }
  20.  
  21.   int get_super_parent(int x)
  22.   {
  23.     if(par[x] == x) return x;
  24.     else return par[x] = get_super_parent(par[x]);
  25.   }
  26.  
  27.   void merge(int x,int y)
  28.   {
  29.     int super_par_x = get_super_parent(x);
  30.     int super_par_y = get_super_parent(y);
  31.  
  32.     if(super_par_x != super_par_y)
  33.     {
  34.       par[super_par_x]=super_par_y;
  35.       total_comp--;
  36.     }
  37.   }
  38. };
  39.  
  40. void solve()
  41. {
  42.   int n,m;
  43.   cin>>n>>m;
  44.   dsu_struct dsu;
  45.   dsu.init(n);
  46.   while(m--)
  47.   {
  48.     int u,v;
  49.     cin>>u>>v;
  50.     dsu.merge(u,v);
  51.   }
  52.   cout<<dsu.total_comp - 1<<"\n";
  53.   for(int i=1;i<n;i++)
  54.   {
  55.     if(dsu.get_super_parent(i) != dsu.get_super_parent(i + 1))
  56.       cout<<i<<" "<<i+1<<"\n";
  57.      dsu.merge(i,i+1);
  58.   }
  59. }
  60.  
  61. int main()
  62. {
  63.   IOfast;
  64.   solve();
  65.   return 0;
  66. }
  67.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement