写出:运用Kruskal算法完成校园网络遍历与最小生成树的最小生成树:按Kruskal算法的求解顺序,依次显示构成最小生成树的各条边,并且显示最小生成树的代价的代码
时间: 2024-04-13 19:23:07 浏览: 103
最小生成树的Kruskal算法实现
使用Kruskal算法完成校园网络遍历与最小生成树的最小生成树的代码如下:
```python
# 定义边的数据结构
class Edge:
def __init__(self, src, dest, weight):
self.src = src
self.dest = dest
self.weight = weight
# 定义并查集数据结构
class UnionFind:
def __init__(self, vertices):
self.parent = {}
self.rank = {}
for v in vertices:
self.parent[v] = v
self.rank[v] = 0
def find(self, v):
if self.parent[v] != v:
self.parent[v] = self.find(self.parent[v])
return self.parent[v]
def union(self, v1, v2):
root1 = self.find(v1)
root2 = self.find(v2)
if root1 != root2:
if self.rank[root1] < self.rank[root2]:
self.parent[root1] = root2
elif self.rank[root1] > self.rank[root2]:
self.parent[root2] = root1
else:
self.parent[root2] = root1
self.rank[root1] += 1
# Kruskal算法求解最小生成树
def kruskal(vertices, edges):
# 按边的权重进行排序
edges.sort(key=lambda x: x.weight)
# 初始化并查集
uf = UnionFind(vertices)
# 存储最小生成树的边和代价
mst_edges = []
mst_cost = 0
for edge in edges:
src_root = uf.find(edge.src)
dest_root = uf.find(edge.dest)
# 判断是否形成环路
if src_root != dest_root:
mst_edges.append(edge)
mst_cost += edge.weight
uf.union(src_root, dest_root)
return mst_edges, mst_cost
# 测试代码
if __name__ == "__main__":
vertices = ['A', 'B', 'C', 'D', 'E']
edges = [
Edge('A', 'B', 5),
Edge('A', 'C', 3),
Edge('B', 'C', 1),
Edge('B', 'D', 4),
Edge('C', 'D', 2),
Edge('C', 'E', 6),
Edge('D', 'E', 7)
]
mst_edges, mst_cost = kruskal(vertices, edges)
print("构成最小生成树的边:")
for edge in mst_edges:
print(f"{edge.src} - {edge.dest} : {edge.weight}")
print("最小生成树的代价:", mst_cost)
```
阅读全文