并查集

并查集介绍

在计算机科学中,并查集是一种树型的数据结构,用于处理一些不交集(Disjoint Sets)的合并及查询问题。有一个联合-查找算法union-find algorithm)定义了两个用于此数据结构的操作:

  • Find确定元素属于哪一个子集。这个确定方法就是不断向上查找找到它的根节点,它可以被用来确定两个元素是否属于同一子集
  • Union将两个子集合并成同一个集合

 

python代码

class UnionFindSet(object):
    def __init__(self, unionFindSet):
        self.unionFindSet = unionFindSet
    
    def find(self, x):
        if self.unionFindSet[x] != x:
            self.unionFindSet[x] = self.find(self.unionFindSet[x])
        return self.unionFindSet[x]
    
    def union(self, x, y):
        i = self.find(x)
        j = self.find(y)
        self.unionFindSet[x] = j

 

posted @ 2019-07-09 17:30  xd_xumaomao  阅读(48)  评论(0编辑  收藏  举报