Skip to content

Instantly share code, notes, and snippets.

@kigawas
Created January 20, 2020 14:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kigawas/96c76b161f12f978f30873c315085629 to your computer and use it in GitHub Desktop.
Save kigawas/96c76b161f12f978f30873c315085629 to your computer and use it in GitHub Desktop.
Simple python union find
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