while i < len(left_half) and j < len(right_half): if left_half[i] < right_half[j]: arr[k] = left_half[i] i += 1 else: arr[k] = right_half[j] j += 1 k += 1
while i < len(left_half): arr[k] = left_half[i] i += 1 k += 1
while j < len(right_half): arr[k] = right_half[j] j += 1 k += 1
defprim(vertices, edges): graph = {v: [] for v in vertices} for u, v, weight in edges: graph[u].append((weight, v)) graph[v].append((weight, u)) mst = [] visited = {vertices[0]} # 从第一个顶点开始 edges_heap = graph[vertices[0]] heapq.heapify(edges_heap) while edges_heap: weight, u = heapq.heappop(edges_heap) if u notin visited: visited.add(u) mst.append((vertices[0], u, weight)) # 记录边 for weight, v in graph[u]: if v notin visited: heapq.heappush(edges_heap, (weight, v)) return mst