A Generic DSU template which can be used for all DSU based Questions, hope it helps 🤞
class DSU
{
private: // following best OOP practices
vector<int> size,parent;
public:
DSU(int n) //Constructor
{
for(int i=0;i<=n;i++) // here we set size and parent for each node (0 - - N)
{
size.push_back(1); // initially size of each component is 1 (themselves)
parent.push_back(i); // each node is parent of itself
}
}
int findParent(int node) // [Path compression included : Explained further]
{
if(parent[node]==node) // base case if no other components are attached node is parent of itself
return node;
// below we recursively check for ultimate parent of current node and to compress the path we have just added "parent[node]="
//due to which whatever recursion returns it becomes parent of previous node and as we reach ultimate parent paths of all nodes are compressed
//and all point to ultimate parent which in future gives (O(1)) to check parent
return parent[node]=findParent(parent[node]);
}
void unionSize(int u,int v) // making union of both nodes [doing union by Size preference for optimization]
{
int parentU=findParent(u);
int parentV=findParent(v);
if(parentU==parentV) // if both components have same parent no need to make union
return;
// here we check the size of ultimate parents both components and attach lower sized component to higher sized component
//we do so as at the time of path compression (while finding parent) we need to compress path for
//comparatively less number of newly added components as for component with larger size paths are already compressed
// and if we do opposite time require will be more as more number of components will require path compression to get connected to ultimate parent
if(size[parentU]<size[parentV])
{
parent[parentU]=parentV; // we make V as parent of U as there are less components in U
size[parentV]+=size[parentU]; //and we add up the size of U in V as union is formed and V contains more components now
}
else
{
parent[parentV]=parentU;
size[parentU]+=size[parentV];
}
}
};✅🚩 Do comment if you Understood/not understood and consider upvoting if it helped ✅🚩