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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

并查集 Python实现

發(fā)布時間:2025/3/8 python 16 豆豆
生活随笔 收集整理的這篇文章主要介紹了 并查集 Python实现 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1 # 并查集實現(xiàn) 2 class Node: 3 pass 4 5 class UnionFindSet: 6 def __init__(self, nodes): 7 self.fatherDict = dict() 8 self.sizeDict = dict() 9 for node in nodes: 10 self.fatherDict[node] = node 11 self.sizeDict[node] = 1 12 13 # def findHead(self, node): 14 # father = self.fatherDict.get(node) 15 # if node!=father: 16 # father = self.findHead(father) 17 # self.fatherDict[node] = father 18 # return father 19 20 def findHead(self, node): # 找到當前節(jié)點的頭 21 stack = [] # 每次查詢都會優(yōu)化,經過的節(jié)點會直接指向頭結點 22 father = self.fatherDict[node] 23 while node != father: 24 stack.append(node) 25 node = father 26 father = self.fatherDict[node] 27 while len(stack) > 0: 28 self.fatherDict[stack.pop()] = father 29 return father 30 31 def isSameSet(self, a, b): 32 return self.findHead(a) == self.findHead(b) 33 34 def uion(self, a, b): # 兩集合合并 35 if a is None or b is None: 36 return 37 aHead = self.findHead(a) 38 bHead = self.findHead(b) 39 if aHead != bHead: 40 aSize = self.sizeDict[aHead] 41 bSize = self.sizeDict[bHead] 42 if aSize <= bSize: 43 self.fatherDict[aHead] = bHead 44 self.sizeDict[bHead] = aSize + bSize 45 else: 46 self.fatherDict[bHead] = aHead 47 self.sizeDict[aHead] = aSize + bSize

?

轉載于:https://www.cnblogs.com/icekx/p/9142317.html

總結

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

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