Created
June 5, 2021 10:50
-
-
Save yozaam/b5ed2a579f1ee0304a0eaa720ebccd1c to your computer and use it in GitHub Desktop.
Template classes like DSU for Leetcode Problems
This file contains 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: | |
def __init__(self, n = 1000000000): | |
self.parent = [i for i in range(n)] | |
self.rank = [1] * n | |
def make_set(self,u): | |
self.parent[u] = u | |
self.rank[u] = 1 | |
def find_set(self,u): | |
if self.parent[u] == u: | |
return u | |
self.parent[u] = self.find_set(self.parent[u]) # path compresssion so we don't recompute | |
return self.parent[u] | |
def union_sets(self, u, v): | |
u = self.find_set(u) # because we have to work on their roots | |
v = self.find_set(v) # since root represents the entire set | |
if u != v: | |
if self.rank[u] < self.rank[v]: | |
u, v = v, u # make sure v is smaller | |
self.parent[v] = u | |
self.rank[u] += self.rank[v] # sum of size (or += 1 is rank is depth) | |
# return self.rank[u] # just helpful sometimes |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment