Assignment Session 13
Assignment Session 13
Code :
# Dynamic Disjoint Set Data Structure
# Union-Find
# Dynamic Disjoint Set Data Structure
class DynamicDisjointSetDS:
# Constructor
def __init__(self, n):
if self.parent[vertex] != vertex:
self.parent[vertex] = \
self.getParent(self.parent[vertex])
return self.parent[vertex]
return vertex
# Union by Rank
def Union(self, vertexA, vertexB):
# Parent of Vertex A
x = self.getParent(vertexA)
# Parent of Vertex B
y = self.getParent(vertexB)
else:
self.parent[x] = y
self.degree[y] = (self.degree[y] +
self.degree[x])
# Solve
def Solve(N):
# Declaring the Dynamic Disjoint Set DS
dsu = DynamicDisjointSetDS(N)
# Driver Code
if __name__ == "__main__":
# Total Number of Vertexes
N = 5
Edges = [[1, 2], [2, 3], [4, 3]]
# Solve
Solve(N)
Output : 2
Explanation :
Disjoint Set data structure is used to track a set of elements that are partitioned into
discontinuous (non-overlapping) subsets. This data structure is basically helpful in situations
where we cannot simply use arrays to create intermittent sets due to large inputs of the order of
10^9. To illustrate this point, consider the following problem. We need to find the total number of
connected components on the Graph when the Total Sum of Vertices can be up to 10^9.
The idea to solve this problem is, we will maintain two hash tables. One for parents and the
other for degrees. Parent[V] will give the parent of the component which the Vertex V is part of
and Degree will give the number of vertices in that component. Initially, both Parent and Degree
will be empty. We will keep inserting vertices into the maps sequentially.See the code and the
explanation simultaneously for a better understanding.
Below are the methods used in the code to solve the above problem:
1. getParent(V) → Given the parent of the vertex V, this method recursively finds the
parent of the vertex V (see code), meanwhile we assign all the vertices in that
component to have the same parent. In a disjoint data structure all the vertices in the
same component have the same parent.
2. union() → When building an edge with two vertices of different components, we use the
Union() function to link them together. The parent of the component generated by uniting
the two components will be the parent of the component with the most vertices prior to
the union. The new component's degree is updated correspondingly.
3. getTotalComponent() → Vertex in the same component will have the same parent.
Reference: https://www.geeksforgeeks.org/disjoint-set-data-structures/