Overview

Note

This section requires knowledge of MSTs (minimum spanning trees).

Finding MSTs stems from a #Generic Method that grows the tree by adding one edge at a time.

Generic Method

The generic method starts with an empty tree and grows the MST by adding one #Safe Edge at a time.

def generic_mst(graph):
	tree = []
	while tree != spanning_tree:
		edge = graph.safe_edge
		tree.push(edge)
	return tree

Kruskals

This method keeps uses a disjoint set to keep track of a forest of possible MSTs.

def mst_kruskals(graph):
	mst = {}
	forest = DisjointSet()
	for vertex in graph.vertices:
		forest.makeSet(vertex)
    # Make sure to sort by weight and increasing order
	graph.edges.sort()
	for (u, v) in graph.edges:
		# Check if the edges belong to the same set
		if forest.parent(u) != forest.parent(v):
			mst.add((u, v))
			forest.union(u, v)
	return mst

Prims

Running Time: O(ElogV)

Link to min-heap when doc is created.

This method always maintains a single tree instead of a forest. A min-priority queue is used to keep track of all vertices not added to the final MST.

mst_prim(graph, root):
	# Initalize the vertices
	for vertex in graph.vertices:
		vertex.key = float('inf')
		vertex.predecessor = None
	# Initalize the root vertex and start the queue
	root.key = 0
	min_queue = MinHeap()
	# Add all the vertices to the queue
	for vertex in graph.vertices:
		min_queue.add(vertex)
	# While the queue is not empty
	while not min_queue.is_empty:
		# Add to the MST
		u = min_queue.dequeue()
		# Update the keys of adjacent vertices
		for v in graph.adj[u]:
			if v in min_queue and graph.weight(u, v) < v.key:
				v.predecessor = u
				v.key = graph.weight(u, v)
				min_queue.heapify()

The final MST is given by: A={(v,v.π):vV{r}}

MST = [(u, v) \
	   for u in graph.vertices \
	   for v in graph.adj[u] \
	   if v.predecessor != v and v == u.predecessor]

Definitions

Cut

A cut is defined as the partitioning of all the vertices in a graph into two disjoint subsets by set grouping.

i.e. let a graph G=(V,E), a cut would be (S,VS) separating the vertices in the graph into two disjoint subsets S and VS.

e.g. the orange and tan vertices form a cut (the red line).

Pasted image 20240505103636.png

Cross

An edge crosses the cut if one end of the edge belongs to one disjoint set and the other edge belongs to the other.

i.e. an edge (u,v)E crosses if uS and vSV or vice versa.

e.g. (a,h) crosses the cut; (h,i) does not.

Pasted image 20240505103636.png

Respect

A cut respects a set A (tree to be built) if no edge in A crosses the cut.

e.g. the cut respects the set of blue edges

Pasted image 20240505103636.png

Safe Edge

An edge is considered "safe" if the following conditions are met.

Reference

  1. Sun, Hongyang MST The University of Kansas 2024

Related