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.
This is a great algorithmic question. The user is asking for an implementation of Prim's algorithm using advanced data structures (Fibonacci heap or pairing heap) to achieve the optimal time complexity of O(E + V log V).
Let me break down what's needed:
Prim's Algorithm basics:
Start from any vertex
Maintain a set of vertices in the tree and vertices not in the tree
At each step, find the minimum weight edge from tree vertices to non-tree vertices
Add that edge and the new vertex to the tree
Advanced Data Structures for optimization:
Standard Prim's with min-heap: O((V + E) log V)
With Fibonacci heap: O(E + V log V) because decrease-key is O(1) amortized
The key insight: we need efficient decrease-key operations
Implementation strategy:
I'll provide both Fibonacci heap and Pairing heap implementations
Show how to use them with Prim's algorithm
Provide complete working code with examples
Let me write a comprehensive solution:
python
from typing import List, Tuple, Optional
import math
# Fibonacci Heap Node
class FibNode:
def __init__(self, key, data=None):
self.key = key
self.data = data
self.degree = 0
self.parent = None
self.child = None
self.left = self
self.right = self
self.marked = False
def __lt__(self, other):
return self.key < other.key
# Fibonacci Heap
class FibonacciHeap:
def __init__(self):
self.min_node = None
self.size = 0
def insert(self, key, data=None):
"""Insert a new node with given key and data"""
node = FibNode(key, data)
self.size += 1
if self.min_node is None:
self.min_node = node
else:
self._merge_lists(self.min_node, node)
if node.key < self.min_node.key:
self.min_node = node
return node
def _merge_lists(self, a, b):
"""Merge two circular doubly-linked lists"""
a.right.left = b
b_left = b.left
b.left = a
a.right = b_left
b.left.right = b
def extract_min(self):
"""Extract and return the minimum node"""
min_node = self.min_node
if min_node is None:
return None
# Promote all children to root list
child = min_node.child
if child is not None:
current = child
while True:
current.parent = None
current = current.right
if current == child:
break
self._merge_lists(min_node, child)
# Unlink min_node from root list
if min_node.right == min_node:
self.min_node = None
else:
min_node.left.right = min_node.right
min_node.right.left = min_node.left
self.min_node = min_node.right
self._consolidate()
self.size -= 1
return min_node
def _consolidate(self):
if self.size == 0:
return
max_degree = int(math.log2(self.size)) + 1
degree_table = [None] * (max_degree + 1)
# Collect all nodes currently in root list
nodes_to_process = []
current = self.min_node
while True:
nodes_to_process.append(current)
current = current.right
if current == self.min_node:
break
# Merge trees of same degree until each degree appears once
for node in nodes_to_process:
degree = node.degree
while degree_table[degree] is not None:
other = degree_table[degree]
# Ensure smaller key becomes parent
if node.key > other.key:
node, other = other, node
self._link_nodes(other, node)
degree_table[degree] = None
degree += 1
degree_table[degree] = node
# Rebuild root list with consolidated trees and find new minimum
self.min_node = None
for node in degree_table:
if node is not None:
if self.min_node is None:
self.min_node = node
node.left = node
node.right = node
else:
self._merge_lists(self.min_node, node)
if node.key < self.min_node.key:
self.min_node = node
After consolidating trees by degree, I rebuild the root list and track the minimum node. The `_link_nodes` method removes a child from the root list and attaches it to a parent, incrementing the parent's degree. The `decrease_key` operation updates a node's key and potentially triggers cascading cuts if the heap property is violated.
When decreasing a key, if the new value is smaller than its parent's key, I cut the node from its parent and recursively cut the parent if it's already been marked. The `_cut` method removes a node from its parent's children and adds it back to the root list, while `_cascading_cut` maintains the heap's potential function by marking nodes and cutting marked nodes that lose another child. Finally, I check if the decreased key becomes the new minimum.
For the pairing heap implementation, I initialize the root as null and size to 0. The `insert` operation creates a new node and merges it with the existing root in constant amortized time. When extracting the minimum, I remove the root and recursively merge its children pairwise to rebuild the heap structure. The `_merge` method combines two heaps by making the one with the smaller key the parent, while `_merge_pairs` processes the children list by pairing them up and merging each pair. = node.parent
parent.children.remove(node)
node.parent = None
self.root = self._merge(self.root, node)
def is_empty(self):
return self.size == 0
# Graph representation
class Graph:
def __init__(self, vertices: int):
self.V = vertices
self.edges = []
self.adj = [[] for _ in range(vertices)]
def add_edge(self, u: int, v: int, weight: float):
"""Add an undirected edge"""
self.edges.append((weight, u, v))
self.adj[u].append((v, weight))
self.adj[v].append((u, weight))
# Prim's algorithm with Fibonacci Heap
def prim_fibonacci(graph: Graph, start: int = 0) -> Tuple[float, List[Tuple[int, int, float]]]:
"""
Prim's algorithm using Fibonacci Heap
Time Complexity: O(E + V log V)
Args:
graph: Graph object
start: Starting vertex
Returns:
(total_weight, mst_edges)
"""
V = graph.V
in_tree = [False] * V
fib_heap = FibonacciHeap()
key = [float('inf')] * V
parent = [-1] * V
heap_node = [None] * V
# Initialize with start vertex at key 0
key[start] = 0
heap_node[start] = fib_heap.insert(0, start)
total_weight = 0
mst_edges = []
while not fib_heap.is_empty():
min_key, u = fib_heap.extract_min()
in_tree[u] = True
total_weight += min_key
if parent[u] != -1:
mst_edges.append((parent[u], u, min_key))
for v, weight in graph.adj[u]:
if not in_tree[v] and weight < key[v]:
key[v] = weight
parent[v] = u
if heap_node[v] is None:
heap_node[v] = fib_heap.insert(weight, v)
else:
fib_heap.decrease_key(heap_node[v], weight)
return total_weight, mst_edges
I set up the Fibonacci Heap-based Prim's algorithm by initializing tracking arrays for vertices in the tree, keys, and parent pointers. The start vertex gets key 0 and enters the heap. Then I extract minimum-key vertices one by one, marking them as in the tree and relaxing their adjacent edges—either inserting new vertices into the heap or decreasing keys for already-discovered ones. , 3),
]
for u, v, w in edges:
g.add_edge(u, v, w)
return g
The example graph has 6 vertices with weighted edges connecting them. I'm setting up test cases to verify the implementations work correctly.
For displaying results, I need a function that shows the MST details including total weight and all edges included. Then I'll create a benchmark to compare performance across the different heap implementations.
I'll measure execution time for both Fibonacci and Pairing heap versions of Prim's algorithm on the same graph. After running each algorithm, I'll verify they produce identical total weights and display the timing results in milliseconds for comparison. _weight_fib, mst_edges_fib = prim_fibonacci(g, start=0)
print_mst(total_weight_fib, mst_edges_fib, "Fibonacci Heap")
# Run Prim's with Pairing Heap
total_weight_pair, mst_edges_pair = prim_pairing(g, start=0)
print_mst(total_weight_pair, mst_edges_pair, "Pairing Heap")
# Verify both produce same result
assert total_weight_fib == total_weight_pair
print("\n✓ Both algorithms produce the same MST!")
# Benchmark
benchmark_algorithms()
# Complexity Analysis
print("\n" + "="*70)
print("
TIME COMPLEXITY ANALYSIS")
print("="*70)
print("""
Prim's Algorithm with Advanced Heaps:
1. FIBONACCI HEAP:
- Insert: O(1) amortized
- Extract-Min: O(log V) amortized
- Decrease-Key: O(1) amortized
Total Complexity: O(E + V log V)
Why optimal?
- V insertions: O(V)
- V extract-min: O(V log V)
- E decrease-key ops: O(E)
- Total: O(E + V log V)
2. PAIRING HEAP:
- Insert: O(1) amortized
- Extract-Min: O(log V) amortized
- Decrease-Key: O(1) amortized
The Fibonacci heap achieves O(E + V log V) by leveraging O(1) amortized decrease-key operations, which dominate when handling E edge relaxations. The pairing heap provides similar theoretical bounds with better practical performance due to lower constant factors.
3. STANDARD BINARY HEAP:
- Insert: O(log V)
- Extract-Min: O(log V)
- Decrease-Key: O(log V)
Total Complexity: O((E + V) log V)
SPACE COMPLEXITY: O(V)
The decrease-key operation is what separates optimal from suboptimal implementations. When discovering shorter paths to unvisited vertices, the heap must efficiently update priorities—something Fibonacci heaps handle in constant time versus logarithmic time for binary heaps.
""")
Actually, let me provide a clearer, more complete implementation with better documentation and additional helper functions:
Prim's Algorithm with Advanced Heaps
I'll provide complete implementations of both Fibonacci and Pairing heaps with Prim's algorithm, achieving O(E + V log V) complexity.
1. Fibonacci Heap Implementation
python
2. Pairing Heap Implementation
python
class PairingNode:
"""Node in Pairing Heap"""
def __init__(self, key: float, vertex: int = None):
self.key = key
self.vertex = vertex
self.children = []
self.parent = None
def __lt__(self, other):
return self.key < other.key
class PairingHeap:
"""Pairing Heap - simpler than Fibonacci, similar performance"""
def __init__(self):
self.root = None
self.size = 0
def insert(self, key: float, vertex: int = None) -> PairingNode:
"""Insert node - O(1) amortized"""
node = PairingNode(key, vertex)
self.size += 1
if self.root is None:
self.root = node
else:
self.root = self._merge_heaps(self.root, node)
return node
def extract_min(self) -> Optional[PairingNode]:
"""Extract minimum - O(log V) amortized"""
if self.root is None:
return None
min_node = self.root
self.size -= 1
if not self.root.children:
self.root = None
else:
self.root = self._merge_pairs(self.root.children)
return min_node
def decrease_key(self, node: PairingNode, new_key: float) -> None:
"""Decrease key - O(1) amortized"""
if new_key > node.key:
raise ValueError(f"New key {new_key} > current key {node.key}")
node.key = new_key
if node.parent is None:
# Already at root, just update
if node.key < self.root.key:
self.root = node
else:
# Cut from parent and merge with root
parent = node.parent
node.parent = None
parent.children.remove(node)
self.root = self._merge_heaps(self.root, node)
def _merge_heaps(self, h1: PairingNode, h2: PairingNode) -> PairingNode:
"""Merge two heaps"""
if h1 is None:
return h2
if h2 is None:
return h1
if h1.key <= h2.key:
h1.children.append(h2)
h2.parent = h1
return h1
else:
h2.children.append(h1)
h1.parent = h2
return h2
def _merge_pairs(self, nodes: List[PairingNode]) -> Optional[PairingNode]:
"""Merge list of nodes pairwise"""
if not nodes:
return None
if len(nodes) == 1:
nodes[0].parent = None
return nodes[0]
# First pass: merge pairs
merged = []
for i in range(0, len(nodes), 2):
if i + 1 < len(nodes):
merged.append(self._merge_heaps(nodes[i], nodes[i + 1]))
else:
nodes[i].parent = None
merged.append(nodes[i])
# Second pass: merge results
result = merged[0]
for i in range(1, len(merged)):
result = self._merge_heaps(result, merged[i])
return result
def is_empty(self) -> bool:
return self.size == 0
3. Prim's Algorithm Implementation
python
4. Complete Example and Testing
python
import time
def create_test_graph() -> Graph:
"""Create test graph"""
g = Graph(7)
edges = [
(0, 1, 7),
(0, 3, 5),
(1, 2, 8),
(1, 3, 9),
(1, 4, 7),
(2, 4, 5),
(3, 4, 15),
(3, 5, 6),
(4, 5, 8),
(4, 6, 9),
(5, 6, 11),
]
for u, v, w in edges:
g.add_edge(u, v, w)
return g
def print_mst(total_weight: float, edges: List, algorithm: str):
print(f"\n{'='*60}")
print(f"MST - {algorithm}")
print(f"{'='*60}")
print(f"Total Weight: {total_weight}")
print(f"\nEdges:")
for u, v, w in sorted(edges):
print(f" {u} -- {v}: {w}")
print(f"Number of edges: {len(edges)}")
def benchmark():
"""Benchmark both algorithms"""
print("\n" + "="*60)
print("PERFORMANCE BENCHMARK")
print("="*60)
graph = create_test_graph()
# Fibonacci Heap
start = time.perf_counter()
weight_fib, edges_fib = prim_fibonacci(graph)
time_fib = (time.perf_counter() - start) * 1000
# Pairing Heap
start = time.perf_counter()
weight_pair, edges_pair = prim_pairing(graph)
time_pair = (time.perf_counter() - start) * 1000
print(f"\nFibonacci Heap: {time_fib:.4f} ms (weight: {weight_fib})")
print(f"Pairing Heap: {time_pair:.4f} ms (weight: {weight_pair})")
assert weight_fib == weight_pair == 39, "MST weights mismatch!"
print("✓ Both algorithms produce identical MST!")
# Main execution
if __name__ == "__main__":
graph = create_test_graph()
print("="*60)
print("PRIM'S ALGORITHM WITH ADVANCED HEAPS")
print("="*60)
print("\nGraph Vertices: 7")
print("Graph Edges: 11")
# Run algorithms
weight_fib, edges_fib = prim_fibonacci(graph)
weight_pair, edges_pair = prim_pairing(graph)
print_mst(weight_fib, edges_fib, "Fibonacci Heap")
print_mst(weight_pair, edges_pair, "Pairing Heap")
# Run benchmark
benchmark()
# Complexity analysis
print("\n" + "="*60)
print("COMPLEXITY ANALYSIS")
print("="*60)
print("""
FIBONACCI HEAP:
Insert: O(1) amortized
Extract-Min: O(log V) amortized
Decrease-Key: O(1) amortized ← KEY OPTIMIZATION
Total: O(E + V log V)
Operations count:
- V inserts: O(V)
- V extract-mins: O(V log V)
- E decrease-keys: O(E)
- Total: O(E + V log V)
PAIRING HEAP:
Similar to Fibonacci heap with simpler implementation
Slightly better constants in practice
SPACE: O(V) for both data structures
KEY INSIGHT:
The decrease-key operation is critical. Standard heaps require O(log V)
per decrease-key, but Fibonacci and Pairing heaps achieve O(1) amortized,
making total complexity optimal for dense graphs where E >> V log V.
""")