import heapq
from typing import List, Tuple, Dict, Any
from collections import defaultdict
def prim_mst(graph: Dict[int, List[Tuple[int, float]]], start: int = 0) -> List[Tuple[int, int, float]]:
"""
Generates a Minimum Spanning Tree (MST) using Prim's algorithm.
Args:
graph: Adjacency list representation where graph[u] = [(v1, weight1), (v2, weight2), ...]
Assumes undirected, connected, weighted graph with non-negative weights.
start: Starting vertex (default 0).
Returns:
List of edges in the MST as [(u, v, weight), ...].
Time Complexity: O(E log V) using binary heap.
Space Complexity: O(V).
"""
vertices = list(graph.keys())
n = len(vertices)
if n == 0:
return []
# Map vertex labels to indices if they are not consecutive integers starting from 0
vertex_to_idx = {v: i for i, v in enumerate(vertices)}
start_idx = vertex_to_idx[start]
# Key values to select minimum weight edge
key = [float('inf')] * n
key[start_idx] = 0
# Parent array to reconstruct MST
parent = [-1] * n
# Min-heap: (key_value, vertex_index)
pq: List[Tuple[float, int]] = []
heapq.heappush(pq, (0, start_idx))
# Visited array
visited = [False] * n
while pq:
_, u = heapq.heappop(pq)
if visited[u]:
continue
visited[u] = True
# Update adjacent vertices
for v, weight in graph[vertices[u]]:
v_idx = vertex_to_idx[v]
if not visited[v_idx] and weight < key[v_idx]:
key[v_idx] = weight
parent[v_idx] = u
heapq.heappush(pq, (weight, v_idx))
# Reconstruct MST edges
mst_edges = []
for i in range(n):
if parent[i] != -1:
u = vertices[parent[i]]
v = vertices[i]
w = key[i]
mst_edges.append((u, v, w))
return mst_edges
Example Usage
# Example graph: vertices 0-4
graph = {
0: [(1, 10), (3, 5)],
1: [(0, 10), (2, 1), (3, 2)],
2: [(1, 1), (3, 4), (4, 8)],
3: [(0, 5), (1, 2), (2, 4), (4, 2)],
4: [(2, 8), (3, 2)]
}
mst = prim_mst(graph, start=0)
print(mst) # Example output: [(0, 3, 5.0), (3, 1, 2.0), (1, 2, 1.0), (3, 4, 2.0)]
This implementation handles arbitrary vertex labels (e.g., strings or integers) via indexing and uses a binary heap for efficient minimum extraction. It skips duplicates in the heap for simplicity (works well in practice). The total weight of the MST is sum(w for _, _, w in mst).