00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037
00038
00039
00040
00041
00042
00043 # ifndef KRUSKAL_H
00044 # define KRUSKAL_H
00045
00046 # include <ahFunction.H>
00047 # include <tpl_graph.H>
00048 # include <tpl_graph_utils.H>
00049
00050 using namespace Aleph;
00051
00052 namespace Aleph {
00053
00103 template <class GT, class Distance, class Compare> inline
00104 void kruskal_min_spanning_tree(GT & g, GT & tree)
00105 {
00106
00107 if (g.is_digraph())
00108 throw std::domain_error("g is a digraph");
00109
00110 if (not test_connectivity(g))
00111 throw std::invalid_argument("Input graph is not connected");
00112
00113 g.reset_bit_nodes(Aleph::Kruskal);
00114
00115 tree.clear_graph();
00116
00117 g.template sort_arcs<Distance_Compare<GT, Distance, Compare> >();
00118
00119
00120 for (typename GT::Arc_Iterator arc_itor(g);
00121 tree.get_num_arcs() < g.get_num_nodes() - 1; arc_itor.next())
00122 {
00123 typename GT::Arc * arc = arc_itor.get_current_arc();
00124
00125 typename GT::Node * g_src_node = g.get_src_node(arc);
00126
00127 typename GT::Node * tree_src_node;
00128
00129 if (not IS_NODE_VISITED(g_src_node, Aleph::Kruskal))
00130 {
00131 NODE_BITS(g_src_node).set_bit(Aleph::Kruskal, true);
00132 tree_src_node = tree.insert_node(g_src_node->get_info());
00133 GT::map_nodes(g_src_node, tree_src_node);
00134 }
00135 else
00136 tree_src_node = static_cast<typename GT::Node*>(NODE_COOKIE(g_src_node));
00137 typename GT::Node * g_tgt_node = g.get_tgt_node(arc);
00138 typename GT::Node * tree_tgt_node;
00139 if (not IS_NODE_VISITED(g_tgt_node, Aleph::Kruskal))
00140 {
00141 NODE_BITS(g_tgt_node).set_bit(Aleph::Kruskal, true);
00142 tree_tgt_node = tree.insert_node(g_tgt_node->get_info());
00143 GT::map_nodes(g_tgt_node, tree_tgt_node);
00144 }
00145 else
00146 tree_tgt_node = static_cast<typename GT::Node*>(NODE_COOKIE(g_tgt_node));
00147
00148 typename GT::Arc * arc_in_tree =
00149 tree.insert_arc(tree_src_node, tree_tgt_node, arc->get_info());
00150
00151 if (has_cycle(tree))
00152 {
00153 tree.remove_arc(arc_in_tree);
00154 continue;
00155 }
00156 GT::map_arcs(arc, arc_in_tree);
00157 }
00158 }
00159
00160 template <class GT, class Distance> inline
00161 void kruskal_min_spanning_tree(GT & g, GT & tree)
00162 {
00163 typedef typename Distance::Distance_Type DT;
00164
00165 kruskal_min_spanning_tree<GT, Distance, Aleph::less<DT> > (g, tree);
00166 }
00167
00168
00169 }
00170
00171 # endif // KRUSKAL_H