关于并查集的Python实现代码

Time: 20190924

class UnionFind:
    def __init__(self, nums):
        # 初始时元素是自己的大boss
        self.pre = list(range(nums))
        self.size = [1] * nums
    
    def union(self, x, y):
        px = self.find(x)
        py = self.find(y)

        # 是的px这组的size比较小
        if self.size[px] > self.size[py]:
            px, py = py, px
        # 小的团队交给大的
        self.pre[px] = py
        self.size[py] += self.size[px]

    def find_recur(self, x):
        # 递归写法并没有执行路径压缩~
        if self.pre[x] != x:
            self.pre[x] = self.find(x)
        return self.pre[x]
        
    def find(self, x):
        r = x
        while self.pre[r] != r:
            r = self.pre[r]
            i = x
            while i != r:
                tmp = self.pre[i]
                self.pre[i] = r
                i = tmp
        return r

# Driver code
uf = UnionFind(10)
print(uf.pre)
# 
uf.find(1)
print("执行find之后:", uf.pre)
uf.union(1,2)
print("执行Union之后:", uf.pre)
uf.union(2,3)
print("执行Union之后:", uf.pre)
uf.union(3, 4)
print("执行Union之后:", uf.pre)

# 查看元素的父亲
# print(uf.find(1)) # 4
# print(uf.find(2)) # 4
# print(uf.find(3)) # 4
# print(uf.find(4)) # 4

for i in uf.pre:
    print(uf.find(i))

2019.10 Update:

第一届PAT算法直播课培训班招募帖,欢迎点击查看详情、

END.

你可能感兴趣的:(算法学习)