Last active
January 25, 2018 16:50
-
-
Save cocodrips/35f83d9524ee6f618e73 to your computer and use it in GitHub Desktop.
Union Find in Python
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 UnionFind: | |
def __init__(self, n): | |
self.par = range(n) | |
self.rank = [0 for i in xrange(n)] | |
def find(self, x): | |
if self.par[x] == x: | |
return 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 x == y: | |
return | |
if self.rank[x] < self.rank[y]: | |
self.par[x] = y | |
else: | |
self.par[y] = x | |
if self.rank[x] == self.rank[y]: | |
self.rank[x] += 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment