1 #and check the realization of the Set2 classNode:3 Pass4 5 classUnionfindset:6 def __init__(self, nodes):7Self.fatherdict =dict ()8Self.sizedict =dict ()9 forNodeinchnodes:TenSelf.fatherdict[node] =node OneSelf.sizedict[node] = 1 A - #def findhead (Self, node): - #father = Self.fatherDict.get (node) the #if Node!=father: - #father = Self.findhead (father) - #Self.fatherdict[node] = Father - #return Father + - defFindhead (Self, node):#Locate the header of the current node +stack = []#each query is optimized, and the passing node points directly to the head node AFather =Self.fatherdict[node] at whileNode! =Father: - stack.append (node) -node =Father -Father =Self.fatherdict[node] - whileLen (Stack) >0: -Self.fatherdict[stack.pop ()] =Father in returnFather - to defIssameset (self, A, b): + returnSelf.findhead (a) = =Self.findhead (b) - the defUion (self, A, b):#two integrated merger * ifA isNoneorB isNone: $ returnPanax NotoginsengAHead =Self.findhead (a) -Bhead =Self.findhead (b) the ifAHead! =Bhead: +Asize =Self.sizedict[ahead] ABsize =Self.sizedict[bhead] the ifAsize <=bsize: +Self.fatherdict[ahead] =Bhead -Self.sizedict[bhead] = asize +bsize $ Else: $Self.fatherdict[bhead] =AHead -Self.sizedict[ahead] = asize + bsize
And look up Python implementations