题目:
如何设计网络布线,将这所大学的各个单位连通起来,并且使费用最少呢?
备注:代码的无向连通带权图用的是简略图
# 引入堆
import heapq
# 普利姆函数
def prim(graph):
# 从图中随机选择一个节点作为起始节点
start_node = list(graph.keys())[0]
visited = set() # 存储已访问过的节点
min_spanning_tree = [] # 存储最小生成树的边
total_cost = 0 # 总花费
# 使用优先队列来存储边和对应的权重
edge_heap = [(0, start_node, None)] # (权重, 目标节点, 源节点)
while edge_heap:
weight, current_node, parent_node = heapq.heappop(edge_heap)
if current_node not in visited:
visited.add(current_node)
if parent_node is not None:
min_spanning_tree.append((parent_node, current_node, weight))
total_cost += weight
for neighbor, neighbor_weight in graph[current_node].items():
if neighbor not in visited:
heapq.heappush(
edge_heap, (neighbor_weight, neighbor, current_node))
return min_spanning_tree, total_cost
# 用字典表示各点之间的距离
graph = {
'1': {'2': 23, '6': 28, '7': 36},
'2': {'1': 23, '3': 20, '7': 1},
'3': {'2': 20, '4': 15, '7': 4},
'4': {'3': 15, '5': 3, '7': 9},
'5': {'4': 3, '6': 17, '7': 16},
'6': {'1': 28, '5': 17, '7': 25},
'7': {'1': 36, '2': 1, '3': 4, '4': 9, '5': 16, '6': 25}
}
result, cost = prim(graph)
print("Minimum Spanning Tree:")
for edge in result:
print(edge)
print("Total Cost:", cost)