Created
January 20, 2020 14:30
-
-
Save kigawas/96c76b161f12f978f30873c315085629 to your computer and use it in GitHub Desktop.
Simple python union find
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 UF: | |
def __init__(self, n): | |
self.par = list(range(n)) | |
self.rank = [0] * n | |
def find(self, x): | |
if x != self.par[x]: | |
self.par[x] = self.find(self.par[x]) | |
return self.par[x] | |
def same(self, x, y): | |
return self.find(x) == self.find(y) | |
def union(self, x, y): | |
x = self.find(x) | |
y = self.find(y) | |
if self.rank[x] > self.rank[y]: | |
self.par[y] = x | |
else: | |
self.par[x] = y | |
if self.rank[x] == self.rank[y]: | |
self.rank[y] += 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment