# Minimum Spanning Tree CSE 331 Section 2 James Daly.

## Presentation on theme: "Minimum Spanning Tree CSE 331 Section 2 James Daly."— Presentation transcript:

Minimum Spanning Tree CSE 331 Section 2 James Daly

Reminders Project 3 is out Covers graphs Due tomorrow

Review: Graphs G = (V, E) G is a graph V is a set of vertices / nodes E is a set of edges between vertices A vertex u is adjacent to vertex v if and only if the edge uv is in E

Graph Example V2V2 V1V1 V3V3 V5V5 V4V4 V1 is connected to V3 but not to V4

Weighted Graphs Edges or arcs may have weights V2V2 V1V1 V3V3 V5V5 V4V4 5 10 0 7.5 100 7

Network The utility company is laying down new cables A path must exist between every pair of houses What is the lowest possible cost? 40 32 25 20 28 30 35

Minimum Spanning Tree

Example A BC 9 6 5 A BC 9 6 A BC 9 5 A BC 6 5 151411

Trees Trees are connected, acyclic graphs Every pair of vertices is connected by a path Deleting an edge makes T not connected Has no cycles |E| = |V| - 1

Prim’s Algorithm Finds MSTs Greedy algorithm Builds a spanning tree one vertex at a time Start from any vertex At each step, add the closest unincluded vertex Stop when all vertices are added

Prim(G) Q ← V with Key[v] = ∞ // Priority Queue Key[s] ← 0 // Decrease Key While (Q not empty) u ← Q.ExtractMin() For each v in Neighbors(u) If v in Q and w(u, v) < Key[v] Key[v] ← w(u, v) P[v] ← u // Parent in tree Runtime: |V| * ExtractMin = O(|V| log |V|) Runtime: |E| * DecreaseKey = O(|E| log |V|) Total Runtime: O((|V| + |E|) log |V|)

Example A B C D E F G H I 2 7 4 5 8 4 6 7 6 2 9 3 0 2 7 4 4 7 7 5 7 2 3

Proof of Correctness Theorem: The tree T built by Prim’s algorithm is always a subtree of some MST, T 0 for G A single vertex with no edge is trivially true Now suppose for induction that T is contained in T 0 Let uv be the lowest weight edge connecting a vertex u in T to a vertex v not in T If uv is in the MST, then T U uv is also contained in the MST

Proof of Correctness Otherwise T 0 contains some other path P connecting u to v because it spans G P must contain an edge xy connecting some x in T to y not in T If we remove xy from T 0 and add uv, we get a new spanning tree Adding uv creates a cycle that contains xy Removing xy breaks the cycle but does not disconnect anything

Proof of Correctness Since uv is minimal, w(u, v) ≤ w(x, y) Hence the cost of T’ is W(T’) = W(T 0 ) – w(x, y) + w(u, v) ≤ W(T 0 ) Thus either: W(T’) = W(T 0 ) and T’ is a MST containing T U uv or T 0 was never a MST to begin with (a contradiction)

Kruskal’s Algorithm Also finds MSTs Greedy Algorithm Start with a forest Pick the smallest edge that connects to trees Repeat until everything is connected

Kruskal(G) DisjointSets{V} Sol = () For uv in Sorted(E): uset <- FindSet(u) vset <- FindSet(v) If (uset ≠ vset): UnionSets(uset, vset) Sol <- uv Return Sol

Example A B C D E F G H I 2 7 4 5 8 4 6 7 6 2 9 3 7