Skip to content

Instantly share code, notes, and snippets.

@e-mon
Last active February 4, 2016 04:28
Show Gist options
  • Save e-mon/a2c6216a740fe3e6779d to your computer and use it in GitHub Desktop.
Save e-mon/a2c6216a740fe3e6779d to your computer and use it in GitHub Desktop.
class UnionFind:
def __init__(self, N):
self.rank = [0]*N
self.par = list(range(N))
def find(self, x):
if x != self.par[x]:
self.par[x] = self.find(self.par[x])
return self.par[x]
def unite(self, x, y):
x, y = self.find(x), 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