Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- #define all(x) x.begin(),x.end()
- #define pb push_back
- #define IOfast ios_base::sync_with_stdio(false); cin.tie(NULL);
- using namespace std;
- //dsu struct 1 is the starting
- struct dsu_struct
- {
- vector<int> par; //parent of node
- int total_comp; //total component
- void init(int n)
- { //index 1 is the starting
- total_comp = n;
- par.resize(n+1);
- for(int i=1;i<=n;i++) par[i] = i;
- }
- int get_super_parent(int x)
- {
- if(par[x] == x) return x;
- else return par[x] = get_super_parent(par[x]);
- }
- void merge(int x,int y)
- {
- int super_par_x = get_super_parent(x);
- int super_par_y = get_super_parent(y);
- if(super_par_x != super_par_y)
- {
- par[super_par_x]=super_par_y;
- total_comp--;
- }
- }
- };
- void solve()
- {
- int n,m;
- cin>>n>>m;
- dsu_struct dsu;
- dsu.init(n);
- while(m--)
- {
- int u,v;
- cin>>u>>v;
- dsu.merge(u,v);
- }
- cout<<dsu.total_comp - 1<<"\n";
- for(int i=1;i<n;i++)
- {
- if(dsu.get_super_parent(i) != dsu.get_super_parent(i + 1))
- cout<<i<<" "<<i+1<<"\n";
- dsu.merge(i,i+1);
- }
- }
- int main()
- {
- IOfast;
- solve();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement