并查集python实现

#File Name : 并查集.py

class Node(object):
    pass
#节点里面放啥都行 整形 字符串
class UnionFindSet(object):
    def __init__(self,nodes):
        self.fatherDict = {}
        # key node  value father 一层一层向上找
        self.sizeDict = {}
        # key 节点  value 节点所在集合共有多少个节点
        for node in nodes:
            self.fatherDict[node]= node
            self.sizeDict[node] = 1
        #每个节点的父亲是自己 并且所在的集合为个数为1
        #因为要少挂多 ,所以要找节点数目

    def FindHead(self,node):
        stack = []
        father = self.fatherDict[node]
        while father!=node:
            stack.append(node)
            node = father
            father = self.fatherDict[node]
        while stack:
            self.fatherDict[stack.pop()] = father
        return father

    def isSameSet(self,a,b):
        return self.FindHead(a) == self.FindHead(b)

    def uion(self,a,b):
        if a is None or b is None:
            return
        aHead = self.FindHead(a)
        bHead = self.FindHead(b)
        if aHead!=bHead:
            asize = self.sizeDict[aHead]
            bsize = self.sizeDict[bHead]
            if asize<=bsize:
                self.fatherDict[aHead] = bHead
                self.sizeDict[bHead] = asize+bsize
            else:
                self.fatherDict[bHead] = aHead
                self.sizeDict[aHead] = asize+bsize

 

你可能感兴趣的:(算法牛人之路)