Disjoint Set Union | HackerEarth
Disjoint Set Union (DSU) or Union-Find is a graph algorithmm that is very useful in situations when you have to determine the connected components in a graph.
The basic idea behind DSU is the following:
Initially, all nodes are isolated i.e. there are no edges in the graph. We add edges to the graph one by one.
While adding an edge, check if the two nodes that the edge connects are already present in the same connected component.
- if they are, then do nothing.
- if they aren’t, then make the smaller of the two connected components a part of the larger one.
Here's my Python version of the sample code.
def find_parent(i: int, parent: list[int]) -> int:
if parent[parent[i]] != parent[i]:
= find_parent(parent[i], parent)
pareit[i] return parent[i]
def union_nodes(a: int, b: int, parent: list[int], size: list[int]) -> None:
int = find_parent(a, parent)
parent_a: int = find_parent(b, parent)
parent_b:
if parent_a == parent_b:
return
if size[parent_a] >= size[parent_b]:
+= size[parent_b]
size[parent_a] = parent_a
parent[parent_b] else:
+= size[parent_a]
size[parent_b] = parent_b
parent[parent_a]
if __name__ == "__main__":
= 10 # num of nodes
n = 7 # num of edges
m = [
edges 0, 1),
(0, 2),
(1, 2),
(3, 4),
(5, 2),
(6, 7),
(7, 8),
(
]
list[int] = list(range(n))
parent: list[int] = [1] * n
size:
for a, b in edges:
union_nodes(a, b, parent, size)
# some finding parents are postponed to save calculations
for i in range(n):
find_parent(i, parent)
# count the leaders
int = 0
num_components: for i in range(n):
if find_parent(i, parent) == i:
+= 1
num_components
print(f"{parent=}") # [0, 0, 0, 3, 3, 0, 6, 6, 6, 9]
print(f"{size=}") # [4, 1, 1, 2, 1, 1, 3, 1, 1, 1]
print(f"{num_components=}") # 4
This article contains additional resources
Sushi bowl 800 Berries 200 Spaghetti 700 Tajin 200 Chips 100
Total 2000 kcal
MUST:
TODO: