1. 程式人生 > >圖及演算法----並查集父親查詢寫法比較 DisjointSet

圖及演算法----並查集父親查詢寫法比較 DisjointSet

1. 花式查詢並查集

 

 

 

 

 

 

 
 

 



class
DisjointSet: def __init__(self, n): # Args: # n (int): Number of vertices in the graph self.parent = [None] * n # Contains which node is the parent of the node at poisition <i>
self.size = [1] * n # Contains size of node at index <i>, used to optimize merge for i in range(n): self.parent[i] = i # Make all nodes his own parent, creating n sets. def find_set(self, a): if self.parent[a] != a: # Very important, memoize result of the recursion in the list to optimize next
# calls and make this operation practically constant, O(1) self.parent[a] = find_set(self.parent[a]) # node <a> it's the set root, so we can return that index return self.parent[a] def find_set2(self, a): parent_n = a parent_n1 = self.parent[parent_n]
while parent_n1 != parent_n: time.sleep(2) parent_n = parent_n1 parent_n1 = self.parent[parent_n] print(parent_n1, parent_n, a) return parent_n1 def find_set3(self, a): visited, que = set(), [a] u = self.parent[a] while que: time.sleep(2) u = que.pop() if u not in visited: print(f"u={u} was visited") visited.add(u) que.append(self.parent[u]) return u def find_set4(self, a): parent_n1 = a while 1: time.sleep(2) parent_n = parent_n1 parent_n1 = self.parent[parent_n] if parent_n1 == parent_n: break print(parent_n1, parent_n, a) return parent_n1 def find_set5(self, a): parent_n = a while 1: time.sleep(2) parent_n1 = self.parent[parent_n] if parent_n1 == parent_n: break parent_n = parent_n1 print(parent_n1, parent_n, a) return parent_n1 def find_set6(self, a): parent_n = a parent_n1 = self.parent[parent_n] while 1: if parent_n1 != parent_n: # 收斂條件 break time.sleep(2) parent_n = parent_n1 parent_n1 = self.parent[parent_n] print(parent_n1, parent_n, a) return parent_n1