If each edge e has an associated cost c(e)
then the cost of the spanning tree is
c(G) = ∑e in T
( c(e) )
A minimum spanning tree (MST) is a spanning tree of minimum cost.
PrimMST
T := Ø
VT := {x0}
while VT ≠ V do
choose e = (x, y) in VT × (V-VT) of min cost
T := T union {e}
VT := VT union {y}
Prim
T := Ø
VSET[1] := Tree
for v := 2 to n do
VSET[v] := Other
x := 1
CAND := Λ
for TCOUNT := 0 to n-1 do
P := ADJ[x]
while P ≠ λ do
v := NODE[P]
c := COST[P]
P := NEXT[P]
if (VSET[v] = Candidate) and (c < CDIST[v]) then
CNODE[v] := x
1: CDIST[v] := c /** may affect CAND **/
else if VSET[v] = Other then
VSET[v] := Candidate
CNODE[v] := x
CDIST[v] := c
2: CAND ⇐ v
endwhile
3: x := vertex on list CAND that has minimum value of CDIST[vertex]
4: delete x from CAND
VSET[x] := Tree
T := T union (x, CNODE[x])
Time analysis
The while loop is executed a total of O(e) times and, outside of the labeled lines, each line takes constant time.
Label 1 may be executed a total of e times. Labels 2, 3, and 4 may each be executed a total of n times.
| Time for |
CAND data structure | ||
|---|---|---|---|
| linked list | simple heap | Fibonacci heap | |
| 1: | 1 | lg n | 1 |
| 2: | 1 | lg n | lg n |
| 3: | n | 1 | 1 |
| 4: | 1 | lg n | lg n |
| Total | O(n2 + e) | O(e log n) | O(e + n log n) |