0001 class UnionFind: 0002 def __init__(self, n): 0003 self.g = self.n = n 0004 self.group = [ k for k in range(n) ] 0005 0006 def find(self, k): 0007 return self.group[k] 0008 0009 def union(self, i, j): 0010 iGroup , jGroup = self.group[i] , self.group[j] 0011 if iGroup == jGroup: 0012 return 0013 for k in range(self.n): 0014 if (self.group[k] == jGroup): 0015 self.group[k] = iGroup 0016 self.g -= 1 0017 0018 def enumerate(self): 0019 print self.group, " [", self.g, "/", self.n, "]"