python路徑壓縮加權並查集

class Unite_and_find(object):
    def __init__(self,nums):
        self.parents = [i for i in range(nums)]
        self.ranks = [0 for _ in range(nums)]
        self.length = nums

    def find(self,x):
        if self.parents[x] == x:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def unite(self,x,y):
        x = self.find(x)
        y = self.find(y)
        if x==y:
            return

        if self.ranks[x]<self.ranks[y]:
            self.parents[x] = y
        else:
            self.parents[y] = x
            if self.ranks[x]==self.ranks[y]:
                self.ranks[x]+=1

    def same(self,x,y):
        return self.find(x)==self.find(y)

    def set_num(self):
        num = 0
        for ind in range(self.length):
            if self.parents[ind]==ind:
                num+=1
        return num
相關文章
相關標籤/搜索