Last active
September 4, 2019 14:34
-
-
Save zengyu714/bfeb5fe6d56a5430c28fad437d7934de to your computer and use it in GitHub Desktop.
Algorithms
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class DSU: | |
""" | |
Disjoint set union with union-by-rank | |
""" | |
def __init__(self, n): | |
# may need to alter the total number, like (n + 1) | |
self.parent = list(range(n)) | |
self.rank = [0] * n | |
# count of dsu | |
self.count = n | |
def find(self, x): | |
if self.parent[x] != x: | |
self.parent[x] = self.find(self.parent[x]) | |
return self.parent[x] | |
def union(self, x, y): | |
i, j = self.find(x), self.find(y) | |
if i != j: | |
if self.rank[i] < self.rank[j]: | |
self.parent[i] = j | |
elif self.rank[i] > self.rank[j]: | |
self.parent[j] = i | |
else: | |
self.parent[i] = j | |
self.rank[j] += 1 | |
self.count -= 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment