python 基于列表的并查集实现模板

class UnionFind:
    def __init__(self, n::
        self.father = list(range(n))
        self.size = [1] * n
        self.n = n
        # 当前连通分量数目
        self.setCount = n
    
    def find(self, x):
        if self.father[x] == x:
            return x
        self.father[x] = self.find(self.father[x])		
        return self.father[x]

    
    def merge(self, x, y):
        x, y = self.find(x), self.find(y)
        if x == y:
            return False
        if self.size[x] < self.size[y]:
            x, y = y, x
        self.father[y] = x
        self.size[x] += self.size[y]
        self.setCount -= 1
        return True
    
    def is_connected(self, x, y):
        return self.find(x) == self.find(y)

你可能感兴趣的:(python,知识点记录,python,列表,算法,并查集)