Created
March 28, 2024 12:08
-
-
Save FFFiend/08679de864719a5cedf658bfd77afd93 to your computer and use it in GitHub Desktop.
Union Find Python template
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
""" | |
Union Find template for me. | |
""" | |
MAX_SIZE = 10000005 | |
class UnionFind: | |
def __init__(self): | |
self.height = [0]*MAX_SIZE | |
self.father=[0]*MAX_SIZE | |
for i in range(MAX_SIZE): | |
self.father[i]=i | |
def find(self,a): | |
if self.father[a] != a: | |
self.father[a] = self.find(self.father[a]) | |
return self.father[a] | |
def unite(self,a,b): | |
a_val, b_val = self.find(a), self.find(b) | |
if self.height[a_val]>self.height[b_val]: | |
self.father[b_val]=a_val | |
self.height[a_val] = max(self.height[a_val],self.height[b_val]+1) | |
else: | |
self.father[a_val]=b_val | |
self.height[b_val]=max(self.height[b_val],self.height[a_val]+1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment