Skip to content

Create alternate_disjoint_set.py #2302

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Aug 28, 2020
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions data_structures/disjoint_set/alternate_disjoint_set.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
"""
This code implements a disjoint set using Lists
with added heuristics for efficiency
Union by Rank Heuristic and Path Compression
"""
class DisjointSet:
def __init__(self, set_count):
"""
Initialize with the number of items in each set
and with rank = 1 for each set
"""
self.set_count = set_count
self.max_set = max(set_count)
num_sets = len(set_count)
self.ranks = [1] * num_sets
self.parents = list(range(num_sets))

def merge(self, src, dst):
"""
union by rank
"""
src_parent = self.get_parent(src)
dst_parent = self.get_parent(dst)

if src_parent == dst_parent:
return False

if self.ranks[dst_parent] >= self.ranks[src_parent]:
self.set_count[dst_parent] += self.set_count[src_parent]
self.set_count[src_parent] = 0
self.parents[src_parent] = dst_parent
if self.ranks[dst_parent] == self.ranks[src_parent]:
self.ranks[dst_parent] += 1
joined_set_size = self.set_count[dst_parent]
else:
self.set_count[src_parent] += self.set_count[dst_parent]
self.set_count[dst_parent] = 0
self.parents[dst_parent] = src_parent
joined_set_size = self.set_count[src_parent]

self.max_set = max(self.max_set, joined_set_size)
return True

def get_parent(self, set):
"""
Find Parent and Compress Path
"""
if self.parents[set] == set:
return set
self.parents[set] = self.get_parent(self.parents[set])
return self.parents[set]