并查集计算连通分量(python)

class UnionFind():
    def __init__(self):
        self.father = {
     }
        self.size = 0

    def find(self, x):
        root = x
        while self.father[root] is not None:
            root = self.father[root]

        return root

    def merge(self, x, y):
        root_x = self.find(x)
        root_y = self.find(y)

        if root_x != root_y:
            self.father[root_x] = self.father[root_y]
            self.size -= 1

    def add(self, x):
        if x not in self.father:
            self.father[x] = None
            self.size += 1


uf = UnionFind()
for i in range(1, 6):
    uf.add(i)

uf.merge(1, 2)
uf.merge(2, 3)
uf.merge(4, 5)

print(uf.size)

你可能感兴趣的:(知识点记录,python,python)