数据结构之并查集:路径压缩继续优化并查集——20
生活随笔
收集整理的這篇文章主要介紹了
数据结构之并查集:路径压缩继续优化并查集——20
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
路徑壓縮繼續優化并查集
在實現的并查集中,在合并操作merge(item1, item2)時,會不管兩個元素所在的分組大小,總是將item
1的分組合并到item2的分組,這樣可能會導致樹的深度無必要地增加:
如果是大樹合并到小樹上,會導致樹的深度增加,進而造成增刪改查等操作的代價增大
因此我們要對并查集的合并操作進行優化。
優化合并方式
- 每次合并時,都將小分組的元素往大分組合并,由于本例初始化都是一個元素,對應一個分組,它合并的情況可能會變成如下這樣(箭頭代表分組之間的edge),類似一顆星狀的樹:
屬性和方法說明
Python代碼實現及測試
class UF_Tree_Weighted:def __init__(self, n):self.num_groups = nself.groups = [i for i in range(n)]self.nums_in_each_group = [1 for _ in range(n)]def count_groups(self):return self.num_groupsdef in_the_same_group(self, item1, item2):return self.which_group(item1) == self.which_group(item2)def which_group(self, item):"""Find item's root------>groups[groups[groups[...groups[item]...]]]"""while self.groups[item] != item:item = self.groups[item]return itemdef unite(self, item1, item2):p = self.which_group(item1)q = self.which_group(item2)if p == q:returnif self.nums_in_each_group[p] <= self.nums_in_each_group[q]:# Merge the smaller group into the bigger'sself.nums_in_each_group[q] += self.nums_in_each_group[p]self.nums_in_each_group[p] = 0# Change the smaller group-number to the bigger's group-numberself.groups[p] = self.groups[q]else:# Merge the smaller group into the bigger'sself.nums_in_each_group[p] += self.nums_in_each_group[q]self.nums_in_each_group[q] = 0self.groups[q] = self.groups[p]# Numbers of group subtract 1self.num_groups -= 1if __name__ == '__main__':UF = UF_Tree_Weighted(5)print(f"The initial number of groups is {UF.num_groups}")while True:p = int(input(f'Input the to-be-merge element: '))q = int(input(f"Merge to the target element's group: "))if UF.in_the_same_group(p, q):print(f"They are already in the same group")continueUF.unite(p, q)print(f"The number of groups now is {UF.count_groups()}")print(UF.groups)print(f"Elements in each group: {UF.nums_in_each_group}")運行結果
The initial number of groups is 5 Input the to-be-merge element: 0 Merge to the target element's group: 1 The number of groups now is 4 [1, 1, 2, 3, 4] Elements in each group: [0, 2, 1, 1, 1] Input the to-be-merge element: 1 Merge to the target element's group: 2 The number of groups now is 3 [1, 1, 1, 3, 4] Elements in each group: [0, 3, 0, 1, 1] Input the to-be-merge element: 3 Merge to the target element's group: 2 The number of groups now is 2 [1, 1, 1, 1, 4] Elements in each group: [0, 4, 0, 0, 1] Input the to-be-merge element: 2 Merge to the target element's group: 4 The number of groups now is 1 [1, 1, 1, 1, 1] Elements in each group: [0, 5, 0, 0, 0] Input the to-be-merge element:當調用unite()合并時,合并時不考慮參數的先后位置,而是考慮分組的大小,總是會有小的分組合并到大的分組
總結
以上是生活随笔為你收集整理的数据结构之并查集:路径压缩继续优化并查集——20的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 怎么样批量修改html里的内容,批量修改
- 下一篇: c语言文件压缩与解压缩实验报告,哈弗曼树