1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
| import numpy as np import sympy as sp from DataFrame import priority_queue
class Dsu: ''' 并查集 ''' def __init__(self, size): self.size = size self.parent = np.arange(size) self.rank = np.zeros(size)
def find(self, x): ''' 查找节点 ''' if x != self.parent[x]: self.parent[x] = self.find(self.parent[x]) return self.parent[x] def is_same(self, x, y): return self.find(x) == self.find(y) def union(self, x, y): x = self.find(x) y = self.find(y) if x == y: return if self.rank[x] < self.rank[y]: x, y = y, x self.parent[y] = x if self.rank[x] == self.rank[y]: self.rank[x] += 1
def __str__(self): return str(self.parent)
def k_search(Gmatrix) -> np.ndarray: vertex_num = len(Gmatrix) vertex = np.arange(vertex_num) dsu = Dsu(vertex_num) edge_q = priority_queue() for i in range(vertex_num): for j in range(i+1,vertex_num): if Gmatrix[i][j] != 0: edge_q.push((i,j),Gmatrix[i][j]) selected_edge = set() while len(selected_edge) < vertex_num-1: if not edge_q.empty(): temp = edge_q.pop_min() _edge = (temp[0],temp[1]) if not dsu.is_same(_edge[0],_edge[1]): selected_edge.add(_edge) dsu.union(_edge[0],_edge[1]) tree_info = list(selected_edge) tree_matrix = np.zeros((vertex_num,vertex_num)) for i in tree_info: tree_matrix[i[0]][i[1]] = Gmatrix[i[0]][i[1]] return tree_matrix
graph_matrix = np.array([ [0,2,4,1,0,0,0], [2,0,0,3,10,0,0], [4,0,0,2,0,5,0], [1,3,2,0,7,8,4], [0,10,0,7,0,0,6], [0,0,5,8,0,0,1], [0,0,0,4,6,1,0]])
r = k_search(graph_matrix) weight_sum = np.sum(r) print('最小生成树的权重和为:', weight_sum) t = sp.Matrix(r) t
|