【输入形式】 输入图的顶点序列及图的边的情况。如样例所示。边的输入以输入-1,-1,-1作为结束。 0,1,6 表示对应的顶点及边是:A到B的边权值为6. 【输出形式】 输出图的最小生成树 【样例输入1】 ABCDEF# 0,1,6 0,2,1 0,3,5 1,2,5 1,4,3 2,4,6 2,5,4 2,3,5 3,5,2 4,5,6 -1,-1,-1 【样例输出1】 (A,C)--1 (D,F)--2 (B,E)--3 (C,F)--4 (B,C)--5 【样例输入2】 ABCDEFG# 0,1,5 0,2,4 0,3,2 0,4,6 1,6,3 2,4,1 3,5,3 4,5,5 5,6,1 -1,-1,-1 【样例输出2】 (C,E)--1 (F,G)--1 (A,D)--2 (B,G)--3 (D,F)--3 (A,C)--4
时间: 2023-07-02 15:19:33 浏览: 191
以下是Python实现的代码:
```python
import sys
def Prim(n, edges):
INF = sys.maxsize
visited = [False] * n
dist = [INF] * n
parent = [-1] * n
graph = [[INF] * n for _ in range(n)]
for i in range(n):
graph[i][i] = 0
for i in range(len(edges)):
u, v, w = edges[i]
graph[u][v] = w
graph[v][u] = w
dist[0] = 0
for _ in range(n):
min_dist = INF
u = -1
for v in range(n):
if not visited[v] and dist[v] < min_dist:
min_dist = dist[v]
u = v
visited[u] = True
for v in range(n):
if not visited[v] and graph[u][v] < dist[v]:
dist[v] = graph[u][v]
parent[v] = u
return parent
def get_edges(n):
edges = []
while True:
line = input()
if line == '-1,-1,-1':
break
u, v, w = map(int, line.split(','))
edges.append((u, v, w))
return edges
def print_MST(n, parent):
for i in range(1, n):
print(f'({chr(parent[i]+65)},{chr(i+65)})--{graph[i][parent[i]]}')
vertex = input().strip('#')
n = len(vertex)
edges = get_edges(n)
parent = Prim(n, edges)
print_MST(n, parent)
```
输入的顶点序列应该是大写字母,本代码中会自动将其转换为0到n-1的整数。输出的最小生成树中的顶点也是大写字母格式。
阅读全文