class DSU {
public:
vector<int> parent;
vector<int> height;
vector<int> size;
DSU(int n){
parent.resize(n,-1);
size.resize(n,1); //stores size of each component. // only use when required otherwise no need
height.resize(n,1);
}
int findRoot(int node){
if(parent[node] == -1){
return node;}
return (parent[node] = findRoot(parent[node]));
}
int Union(int node1 , int node2){
int ra = findRoot(node1);
int rb = findRoot(node2);
if(ra != rb){
if(height[ra] < height[rb]){
parent[ra] = rb;
size[rb] += size[ra]; // only use when required otherwise no need
return size[rb];
}
else if(height[rb] < height[ra]){
parent[rb] = ra;
size[ra] += size[rb]; // only use when required otherwise no need
return size[ra];
}
else{
parent[rb] = ra;
height[ra] ++;
size[ra] += size[rb]; // only use when required otherwise no need
return size[ra];
}
}
return -1;
}
};Happy Learning – If you require any further information, feel free to contact me.

![[Solved] Odd or Even with C++](https://realcoder.techss24.com/wp-content/uploads/2022/07/Solved-Odd-or-Even-with-C-300x200.png)
![[Solved] Change Position with C++](https://realcoder.techss24.com/wp-content/uploads/2022/07/Solved-Change-Position-with-C-300x200.png)
![[Solved] Music Teacher with Java, CPP, Python](https://realcoder.techss24.com/wp-content/uploads/2023/07/Solved-Music-Teacher-with-Java-CPP-Python-300x169.png)