Generate a minimal spanning tree using Prim's algorithm with a Fibonacci heap or pairing heap to optimize decrease-key to O(1) amortized time for total complexity O(E + V log V).
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Providing Prim's MST using a pairing heap with amortized O(1) decrease-key
Here's a Python implementation of Prim's algorithm using a pairing heap that supports efficient decrease-key operations to achieve the desired O(E + V log V) complexity amortized. The pairing heap nodes use a doubly linked sibling list for O(1) cuts during decrease-key. The code includes graph setup, heap operations, and returns the MST edges with their weights.
One of the standard ways to get the optimal (O(E + V\log V)) bound for Prim's algorithm is to use a heap with constant‑time amortized decrease_key. Fibonacci heaps achieve that, but they are quite involved to implement; pairing heaps have similar amortized behaviour and are simpler.
Here's a self–contained implementation in Python that represents an undirected, weighted graph as an adjacency list and runs Prim's algorithm using a pairing heap. It returns the list of edges in the minimum spanning tree:
python
import math
from typing import Dict, List, Tuple, Any, Optional
class PairingHeapNode:
def __init__(self, key: float, value: Any):
self.key = key
self.value = value
self.child: Optional['PairingHeapNode'] = None
self.sibling: Optional['PairingHeapNode'] = None
self.prev: Optional['PairingHeapNode'] = None
self.parent: Optional['PairingHeapNode'] = None
class PairingHeap:
def __init__(self):
self.root: Optional[PairingHeapNode] = None
def merge(self, a: Optional[PairingHeapNode],
b: Optional[PairingHeapNode]) -> Optional[PairingHeapNode]:
if a is None:
return b
if b is None:
return a
# make the smaller key the root
if b.key < a.key:
a, b = b, a
# attach b as the leftmost child of a
b.parent = a
b.prev = None
b.sibling = a.child
if a.child:
a.child.prev = b
a.child = b
return a
def insert(self, key: float, value: Any) -> PairingHeapNode:
node = PairingHeapNode(key, value)
self.root = self.merge(self.root, node)
return node
def _merge_pairs(self, first: Optional[PairingHeapNode]) -> Optional[PairingHeapNode]:
if first is None or first.sibling is None:
return first
a = first
b = first.sibling
rest = b.sibling
a.sibling = b.sibling = None
merged = self.merge(a, b)
return self.merge(merged, self._merge_pairs(rest))
def extract_min(self) -> Optional[PairingHeapNode]:
if self.root is None:
return None
min_node = self.root
# merge the root's subtrees in pairs
self.root = self._merge_pairs(self.root.child)
if self.root:
self.root.parent = None
self.root.prev = None
min_node.child = min_node.sibling = min_node.prev = min_node.parent = None
return min_node
def decrease_key(self, node: PairingHeapNode, new_key: float):
if new_key >= node.key:
return # no-op if key does not decrease
node.key = new_key
if node is self.root:
return
# cut node out of its current position
# fix sibling links
if node.prev:
node.prev.sibling = node.sibling
if node.sibling:
node.sibling.prev = node.prev
# fix parent child pointer
if node.parent and node.parent.child is node:
node.parent.child = node.sibling
node.parent = node.prev = node.sibling = None
# meld back into root
self.root = self.merge(self.root, node)
def prim_mst(graph: Dict[Any, List[Tuple[Any, float]]]) -> List[Tuple[Any, Any, float]]:
"""
graph: dict mapping vertex -> list of (neighbor, weight)
returns list of edges (u,v,w) in the MST
"""
if not graph:
return []
# initialize all keys to infinity
key = {v: math.inf for v in graph}
parent: Dict[Any, Any] = {}
in_mst = set()
heap = PairingHeap()
nodes: Dict[Any, PairingHeapNode] = {}
# insert all vertices into heap
for v in graph:
nodes[v] = heap.insert(key[v], v)
# start from an arbitrary vertex
start = next(iter(graph))
key[start] = 0.0
heap.decrease_key(nodes[start], 0.0)
mst_edges: List[Tuple[Any, Any, float]] = []
while heap.root is not None:
u_node = heap.extract_min()
u = u_node.value
in_mst.add(u)
# if u has a parent, that's an MST edge
if u in parent:
mst_edges.append((parent[u], u, key[u]))
# relax adjacent edges
for v, w in graph[u]:
if v not in in_mst and w < key[v]:
key[v] = w
parent[v] = u
heap.decrease_key(nodes[v], w)
return mst_edges
# Example usage:
if __name__ == "__main__":
G = {
'A': [('B', 4), ('H', 8)],
'B': [('A', 4), ('C', 8), ('H', 11)],
'C': [('B', 8), ('D', 7), ('F', 4), ('I', 2)],
'D': [('C', 7), ('E', 9), ('F', 14)],
'E': [('D', 9), ('F', 10)],
'F': [('C', 4), ('D', 14), ('E', 10), ('G', 2)],
'G': [('F', 2), ('H', 1), ('I', 6)],
'H': [('A', 8), ('B', 11), ('G', 1), ('I', 7)],
'I': [('C', 2), ('G', 6), ('H', 7)]
}
mst = prim_mst(G)
total_weight = sum(w for _, _, w in mst)
print("MST edges:", mst)
print("Total weight:", total_weight)
The pairing heap gives you (O(1)) amortized decrease_key and (O(\log n)) amortized extract_min, so the overall complexity of Prim's algorithm with this heap is (O(E + V\log V)).