Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<algorithm>
- using namespace std;
- typedef struct{
- int root;
- int rank;
- }subset;
- subset set[100010];
- int find(int x){
- if(set[x].root == x){
- return x;
- }
- return set[x].root = find(set[x].root);
- }
- bool isset(int x,int y){
- return find(x) == find(y);
- }
- void unions(int x,int y){
- int rootx = find(x);
- int rooty = find(y);
- if(set[rootx].rank > set[rooty].rank){
- set[rooty].root = rootx;
- }else if(set[rooty].rank > set[rootx].rank){
- set[rootx].root = rooty;
- }else{
- set[rootx].root = rooty;
- set[rooty].rank++;
- }
- }
- bool mycmp(subset a,subset b){
- return a.root < b.root;
- }
- int main()
- {
- int n,m;
- scanf("%d %d",&n,&m);
- for(int i=1;i<=n;i++){
- set[i].root = i;
- set[i].rank = 0;
- }
- for(int i=0;i<m;i++){
- int u,v;
- scanf("%d %d",&u,&v);
- if(!isset(u,v)){
- unions(u,v);
- }
- }
- // for(int i=1;i<=n;i++)printf("%d ",set[i].root);printf("\n");
- // for(int i=1;i<=n;i++)printf("%d ",set[i].rank);printf("\n");
- for(int i=1;i<=n;i++)find(i);
- sort(set+1,set+n+1,mycmp);
- int preindex = 1;
- int count = 0;
- vector<pair<int,int> > ans;
- for(int i=2;i<=n;i++){
- if(set[preindex].root != set[i].root){
- count++;
- ans.push_back({set[preindex].root,set[i].root});
- }
- preindex = i;
- }
- printf("%d\n",count);
- for(int i=0;i<count;i++){
- printf("%d %d\n",ans[i].first,ans[i].second);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment