日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 综合教程 >内容正文

综合教程

python实现并查集

發布時間:2024/6/21 综合教程 21 生活家
生活随笔 收集整理的這篇文章主要介紹了 python实现并查集 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

并查集是這樣的數據結構:有一大堆的數據,把一些元素放在一個集合當中,另外一些元素放在另一個一個集合當中。

對于它的操作有:查看兩個元素是否在一個集合當中、合并兩個元素。 合并的時候采取的策略是這樣的:將兩個元素所在的集合的所有元素一起放入一個集合當中。

這里使用兩個字典來實現并查集:一個字典保存當前節點的父節點的信息,另外一個保持父節點大小的信息。

class UnionFindSet(object):
    """并查集"""
    def __init__(self, data_list):
        """初始化兩個字典,一個保存節點的父節點,另外一個保存父節點的大小
        初始化的時候,將節點的父節點設為自身,size設為1"""
        self.father_dict = {}
        self.size_dict = {}

        for node in data_list:
            self.father_dict[node] = node
            self.size_dict[node] = 1

    def find_head(self, node):
        """使用遞歸的方式來查找父節點

        在查找父節點的時候,順便把當前節點移動到父節點上面
        這個操作算是一個優化
        """
        father = self.father_dict[node]
        if(node != father):
            father = self.find_head(father)
        self.father_dict[node] = father
        return father

    def is_same_set(self, node_a, node_b):
        """查看兩個節點是不是在一個集合里面"""
        return self.find_head(node_a) == self.find_head(node_b)

    def union(self, node_a, node_b):
        """將兩個集合合并在一起"""
        if node_a is None or node_b is None:
            return

        a_head = self.find_head(node_a)
        b_head = self.find_head(node_b)

        if(a_head != b_head):
            a_set_size = self.size_dict[a_head]
            b_set_size = self.size_dict[b_head]
            if(a_set_size >= b_set_size):
                self.father_dict[b_head] = a_head
                self.size_dict[a_head] = a_set_size + b_set_size
            else:
                self.father_dict[a_head] = b_head
                self.size_dict[b_head] = a_set_size + b_set_size

if __name__ == '__main__':
    a = [1,2,3,4,5]
    union_find_set = UnionFindSet(a)
    union_find_set.union(1,2)
    union_find_set.union(3,5)
    union_find_set.union(3,1)
    print(union_find_set.is_same_set(2,5))  # True
 

總結

以上是生活随笔為你收集整理的python实现并查集的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。