SLIDE 4 Prim Algorithm for MST:
start from a node
13
Step 1: pick node D (an arbitrary node)
cost=2 prev=D cost=4 prev=D cost=3 prev=D cost=6 prev=D cost=inf
cost[u]: current cost of connect u to the tree prev[u]: connect to which node in the tree // init cost, pred for each none tree node u, cost[u] = w(u,D) if (u,D) is an edge = inf if (u,D) is not an edge
Currently, min cost to connect F to the tree is 6, via connecting to D
Prim Algorithm for MST:
Connect a node with lowest cost
14
Step 2 to N: grow the tree to connect a node with lowest cost
cost=2 prev=D cost=4 prev=D cost=3 prev=D cost=6 prev=D cost=inf cost=1 prev=C cost=4 prev=D cost=4 prev=C cost=inf cost=2 prev=D Currently, min cost to connect F to the tree is 6, via connecting to D Currently, min cost to connect F to the tree is 4, via connecting to C
u = node with lowest cost to connect to tree add edge (pred(u), u) into tree //update cost and prev all each none tree node v: if w(v,u)<cost[v] cost[v]=w(v,u) prev[v]=u
Prim Algorithm:
Implementation
15
Step 2 to N: grow the tree to connect a node with lowest cost
u <- the node with lowest cost add edge (pred(u), u) into tree //update cost and prev all each none tree node v: if w(v,u)<cost[v] cost[v]=w(v,u) prev[v]=u
cost=1 prev=C cost=4 prev=D cost=4 prev=C cost=inf cost=2 prev=D Add A and (A,C) into the tree, no updates …
Discussion: How to quickly find the node with lowest cost? Recall the cost of nodes will be updated … Priority queue implemented using heap
Summary
- Minimal Spanning Tree Problem
- application: finding the lowest cost way to connect a set of
nodes
- an example of optimization problem
- Greedy algorithm
- myopic, choose what’s looks to be the best option at current
step.
- sometimes lead to optimal solution, sometimes not
- Two MST algorithms
- Kruscal: grow the tree by adding one edge a time (choose the
edge with lowest weight and does not introduce cycle)
- Prim: grow the tree by adding one node a time, choosing the
node with lowest cost to connect to current (sub)-tree
16