这题其实不难,考最小生成树,这里边多过点,稠密图。用prim算法求最小生成树。嗯。。。套模板。这题的n最大1000。这里代码时间复杂度为O(n^2),勉强够过这题,提交后100分,703ms。
python代码
def prim(graph):
n = len(graph)
costs = [99999 for _ in range(n)] # 父结点到该结点的边权值
costs[0] = 0
visited = [False for _ in range(n)]
t = []
while len(t) < n:
# 在costs找最短边,把该最短边的结点加入t,标记为已访问
minCost = 99999
minNode = None
for i in range(n):
if not visited[i] and costs[i] < minCost:
minCost = costs[i]
minNode = i
t.append(minNode)
visited[minNode] = True
# 遍历该结点的边,更新最短边
for edge in graph[minNode]:
if not visited[edge[0]] and edge[1] < costs[edge[0]]:
costs[edge[0]] = edge[1]
return costs
n, m = map(int, input().split())
# 构建带权邻接表
graph = [[] for _ in range(n)]
for i in range(m):
a, b, c = map(int, input().split())
graph[a - 1].append([b - 1, c])
graph[b - 1].append([a - 1, c])
costs = prim(graph)
total = 0
for cost in costs:
total += cost
print(total)