Disjoint Set in C++

Surbhi Jain
1 min readAug 22, 2019

--

There is no STL library in C++ for using the disjoint set data structures which can be used predominantly for problems like finding minimum spanning trees, cycle detection algorithms, Minimum set problem etc.

I have implemented the data structure which can be used directly while making the focus on the algorithmic logic. This is tested and used code.

It is optimized and incorporates two prominant optimizations i.e. union by rank and path compression.

Initial state of each set

class disjoint_set {

int size;

vector<int> parent;

vector<int> rank; //Height of each vertex is saved

public :

disjoint_set(int siz) : size(siz){

parent.resize(size);

rank.resize(size);

for(int i=0; i < size; ++i) {

parent[i]=i;

rank[i]=1;

}

}

bool do_union(int u, int v) {

int p1 = find(u);

int p2 = find(v);

if(p1 == p2)

return false; //Already in same set

//Union by rank

if (rank[p1] >= rank[p2]) {

parent[p2] = p1;

rank[p1] = std::max(rank[p1], 1 + rank[p2]);

rank[p2] = rank[p1];

} else {

parent[p1] = p2;

rank[p2] = std::max(rank[p2], 1 + rank[p1]);

rank[p1] = rank[p2];

}

return true;

}

//Return the parent of vertex v

int find(int v) {

if(v == parent[v])

return v;

else {

int p = find(parent[v]);

parent[v]=p; //Path compression

return p;

}

}

};

--

--

Surbhi Jain
Surbhi Jain

Written by Surbhi Jain

Engineer @ Google | Technology Enthusiast | IIT Delhi | Computer Science

No responses yet