| 1 |
(* |
| 2 |
* This module implements Kruskal's algorithm for minimal cost |
| 3 |
* spanning tree. |
| 4 |
* |
| 5 |
* -- Allen |
| 6 |
*) |
| 7 |
|
| 8 |
structure Kruskal : MIN_COST_SPANNING_TREE = |
| 9 |
struct |
| 10 |
structure P = NodePartition |
| 11 |
structure Q = PriorityQueue |
| 12 |
structure G = Graph |
| 13 |
|
| 14 |
exception Unconnected |
| 15 |
|
| 16 |
fun spanning_tree { weight, < } (G as G.GRAPH G') add_edge u = |
| 17 |
let fun less (e1,e2) = weight e1 < weight e2 |
| 18 |
val Q = Q.create less |
| 19 |
val _ = #forall_edges G' (Q.insert Q) |
| 20 |
val P = P.node_partition G |
| 21 |
fun make_tree(1,u) = u |
| 22 |
| make_tree(M,u) = |
| 23 |
let val e as (i,j,_) = Q.deleteMin Q |
| 24 |
in if P.== P (i,j) then |
| 25 |
make_tree(M,u) |
| 26 |
else |
| 27 |
(P.union' P (i,j); make_tree(M-1,add_edge(e,u))) |
| 28 |
end |
| 29 |
in |
| 30 |
make_tree(#order G' (),u) |
| 31 |
end handle Q.EmptyPriorityQueue => raise Unconnected |
| 32 |
end |
| 33 |
|