def spanning_tree(nodes, edges, randstream): """Given a list of edges, calculate a minimal spanning tree out of them.""" num_nodes = len(nodes) tree = [] partitions = DisjointSet() for i in range(num_nodes): # create a disjoint set where each node is a singleton partition partitions.add(i) for edge in edges: a, b = edge if partitions.find(a) != partitions.find(b): # partitions were unconnected: bridge them together tree.append(edge) partitions.union(a, b) if len(tree) == num_nodes - 1: # minimal spanning tree acquired break return tree
def spanning_tree(nodes, edges, randstream): """Given a list of edges, calculate a minimal spanning tree out of them.""" num_nodes = len(nodes) tree = [] partitions = DisjointSet() for i in range(num_nodes): # create a disjoint set where each node is a singleton partition partitions.add(i) for edge in edges: a, b = edge if partitions.find(a) != partitions.find(b): # partitions were unconnected: bridge them together tree.append(edge) partitions.union(a, b) if len(tree) == num_nodes-1: # minimal spanning tree acquired break return tree
def FindNegativeCircle(G): ''' 有向图G 返回一个负圈 ''' V = G.V E = G.Adjlist #--------------------------------------------- #采用寻找圈方法 Ds = DisjointSet(V) for u in E.keys(): curList = E[u] curNode = curList.head while curNode!=0: v = curNode.data parentU = Ds.find(u) parentV = Ds.find(v) if parentU == parentV: #生成环,找v->u的所有路径的权重 findPath(v,u,V,E,curNode.weight) else: #在不同的树中,这条边不会产生环 Ds.union(parentU,parentV) curNode = curNode.next
from DisjointSet import * print("Criando o conjunto com subconjuntos disjuntos") myDS = DisjointSet() print("Criando uns subconjuntos") for i in range(5): myDS.makeset(i) print("Printando os conjuntos") myDS.print() print("Unindo R conjuntos 1 e 2") myDS.uniaoR(1, 2) myDS.print() print("Unindo R conjuntos 1 e 3") myDS.uniaoR(1, 3) myDS.print() print("Unindo R conjuntos 0 e 1") myDS.uniaoR(0, 1) myDS.print() print("Retornando o representante dos elementos") for i in range(5): print(str(i) + "-->" + str(myDS.find(i))) print("Verificando se 1 e 2 fazem parte do mesmo conjunto") print(myDS.mesmo(1, 2)) print("Verificando se 1 e 4 fazem parte do mesmo conjunto") print(myDS.mesmo(1, 4)) print("União E de 1 e 4") myDS.print() myDS.uniaoE(1, 4) myDS.print()