Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- using namespace std;
- #define MX 100
- int parent[MX];
- int rankParent[MX];
- void makeSet(int n)
- {
- for(int i=0;i<n;i++){
- parent[i]=i;
- rankParent[i]=0;
- }
- }
- int findParent(int x)
- {
- if(x!=parent[x])
- return parent[x]=findParent(parent[x]);
- else return x;
- }
- void unionSet(int x,int y)
- {
- int xRoot =findParent(x);
- int yRoot =findParent(y);
- if(xRoot==yRoot) return;
- if(rankParent[xRoot]<rankParent[yRoot])
- parent[xRoot]=yRoot;
- else if(rankParent[xRoot]>rankParent[yRoot])
- parent[yRoot]=xRoot;
- else {
- parent[yRoot]=xRoot;
- rankParent[xRoot]++;
- }
- }
- void printSet(int n)
- {
- for(int i=0;i<n;i++)
- {
- cout<<"Node is: "<< i <<" Parent is: "<<parent[i]<<" Rank is: "<<rankParent[i]<<"\n";
- }
- }
- int main()
- {
- int n;
- cin>>n;
- makeSet(n);
- unionSet(0,1);
- unionSet(4,2);
- unionSet(3,1);
- unionSet(0,3);
- //unionSet(0,4);
- printSet(n);
- }
Add Comment
Please, Sign In to add comment