Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
Kruskal.H
Go to the documentation of this file.
1
2/*
3 Aleph_w
4
5 Data structures & Algorithms
6 version 2.0.0b
7 https://github.com/lrleon/Aleph-w
8
9 This file is part of Aleph-w library
10
11 Copyright (c) 2002-2026 Leandro Rabindranath Leon
12
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
19
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
22
23 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 SOFTWARE.
30*/
31
32
44# ifndef KRUSKAL_H
45# define KRUSKAL_H
46
47# include <ah-graph-concepts.H>
48
49# include <ahFunction.H>
50# include <tpl_agraph.H>
51# include <tpl_array.H>
52# include <tpl_sort_utils.H>
53# include <tpl_graph_utils.H>
54# include <tpl_test_acyclique.H>
55# include <tpl_union.H>
56# include <ah-errors.H>
57
58namespace Aleph
59{
90 template <AlephGraph GT,
91 class Distance = Dft_Dist<GT>,
92 ArcFilter<GT> SA = Dft_Show_Arc<GT>>
94 {
96 SA sa;
97 bool painted;
98
101 {
102 long count;
103
104 Init_Node() noexcept : count(0) { /* empty */ }
105
106 void operator ()(const GT &, typename GT::Node *p) noexcept
107 {
108 NODE_COUNTER(p) = count++;
109 NODE_BITS(p).set_bit(Aleph::Spanning_Tree, false);
110 }
111 };
112
113 static bool arc_is_in_tree(Fixed_Relation & tree, long i, long j) noexcept
114 {
115 return tree.are_connected(i, j);
116 }
117
118 public:
127 Kruskal_Min_Spanning_Tree(Distance __dist = Distance(), SA __sa = SA())
128 : dist(__dist), sa(__sa), painted(false)
129 {
130 /* empty */
131 }
132
134 [[nodiscard]] bool is_painted() const noexcept { return painted; }
135
137 template <class G, class GT_SA>
139 {
140 GT_SA & sa;
141
142 Paint_Filt(GT_SA & __sa) : sa(__sa) { /* empty */ }
143
153 bool operator ()(typename G::Arc *a) const
155 {
156 if (not static_cast<bool>(sa(a)))
157 return false;
158
160 }
161 };
162
177 {
178 ah_domain_error_if(g.is_digraph()) << "g is a digraph";
179
180 g.reset_bit_arcs(Aleph::Spanning_Tree); // clear arc marking bits
182
183 // The arcs that sa shows, sorted by distance without moving those of
184 // g: List_SGraph keeps its arcs in a set ordered by address, which
185 // sort_arcs() could not reorder. The sort is stable, so that equal
186 // arcs keep the order of g and every run gives the same tree.
188 for (Arc_Iterator<GT, SA> it(g, sa); it.has_curr(); it.next_ne())
189 arcs.append(it.get_current_arc_ne());
190
192
193 const size_t V = g.get_num_nodes();
194
195 Fixed_Relation tree(V);
196
197 // Traverse the sorted arcs until all nodes are in one component
198 for (size_t k = 0; tree.get_num_blocks() > 1 and k < arcs.size(); ++k)
199 { // next smallest arc
200 auto arc = arcs(k);
201 const long i = NODE_COUNTER(g.get_src_node(arc));
202 const long j = NODE_COUNTER(g.get_tgt_node(arc));
203 if (arc_is_in_tree(tree, i, j))
204 continue;
205
206 tree.join(i, j);
207 ARC_BITS(arc).set_bit(Aleph::Spanning_Tree, true);
208 }
209
210 painted = true;
211 }
212
224 void paint_min_spanning_tree(const GT & g, GT & tree)
225 {
227 clear_graph(tree); // clear destination graph
228
229 // A cookie left by an earlier mapping, perhaps to a tree that no
230 // longer exists, would be chained to the new one by map_nodes() and
231 // map_arcs(), so it is cleared first
232 for (typename GT::Node_Iterator it(g); it.has_curr(); it.next_ne())
233 {
234 auto gp = it.get_curr();
235 auto tp = tree.insert_node(gp->get_info());
236 NODE_COOKIE(gp) = nullptr;
237 GT::map_nodes(gp, tp);
238 }
239
240 typedef Paint_Filt<GT, SA> F;
241 for (Arc_Iterator<GT, F> it(g, F(sa)); it.has_curr(); it.next_ne())
242 {
243 auto ga = it.get_current_arc_ne();
244 auto tsrc = mapped_node<GT>(g.get_src_node(ga));
245 auto ttgt = mapped_node<GT>(g.get_tgt_node(ga));
246 auto ta = tree.insert_arc(tsrc, ttgt, ga->get_info());
247 ARC_COOKIE(ga) = nullptr;
248 GT::map_arcs(ga, ta);
249 }
250 }
251
261 void operator ()(const GT & g, GT & tree)
262 {
264 }
265
276 void operator ()(const GT & g)
277 {
279 }
280 };
281} // end namespace Aleph
282
283# endif // KRUSKAL_H
Exception handling system with formatted messages for Aleph-w.
#define ah_domain_error_if(C)
Throws std::domain_error if condition holds.
Definition ah-errors.H:670
C++20 concepts for the protocol shared by graph algorithms.
Standard functor implementations and comparison objects.
List_Graph< Graph_Node< Node_Info >, Graph_Arc< Arc_Info > > GT
static Array create_reserved(const size_t cap)
Build an empty array with room for at least cap items.
Definition tpl_array.H:194
Default distance accessor for arc weights.
void next_ne() noexcept(shows_ne)
Advances the iterator to the next filtered element, as next() does.
Computes the minimum spanning tree of a graph using Kruskal's algorithm.
Definition Kruskal.H:94
bool is_painted() const noexcept
Returns true if the spanning tree has been painted on the graph.
Definition Kruskal.H:134
void paint_min_spanning_tree(const GT &g)
Paints the minimum spanning tree arcs on the graph.
Definition Kruskal.H:176
Kruskal_Min_Spanning_Tree(Distance __dist=Distance(), SA __sa=SA())
Constructor.
Definition Kruskal.H:127
void paint_min_spanning_tree(const GT &g, GT &tree)
Paints the MST on g and copies it to a separate tree graph.
Definition Kruskal.H:224
static bool arc_is_in_tree(Fixed_Relation &tree, long i, long j) noexcept
Definition Kruskal.H:113
void operator()(const GT &g, GT &tree)
Computes the minimum spanning tree using Kruskal's algorithm.
Definition Kruskal.H:261
virtual Node * insert_node(Node *node) noexcept
Insertion of a node already allocated.
Definition tpl_graph.H:535
_Graph_Arc Arc
The node class type.
Definition tpl_graph.H:444
Arc * insert_arc(Node *src_node, Node *tgt_node, void *a)
Definition tpl_graph.H:618
Functor that traverses the nodes of a graph and performs an operation.
Definition tpl_graph.H:3698
Binary relation between a set of integers.
Definition tpl_union.H:82
constexpr size_t get_num_blocks() const noexcept
Return the number of connected blocks, which is the number of equivalence classes.
Definition tpl_union.H:175
void join(size_t i, size_t j)
Insert the pair '(i,j)' in the relation.
Definition tpl_union.H:200
constexpr size_t get_num_nodes() const noexcept
Return the total of nodes of graph.
Definition graph-dry.H:975
Node * get_src_node(Arc *arc) const noexcept
Return the source node of arc (only for directed graphs)
Definition graph-dry.H:1017
bool is_digraph() const noexcept
Return true if the graph this is directed.
Definition graph-dry.H:937
static void map_arcs(A1 *p, A2 *q) noexcept
Map the arcs through their cookies.
Definition graph-dry.H:1312
void reset_bit_arcs(int bit) const noexcept
Reset bit to zero for all the arcs of graph.
Definition graph-dry.H:1332
constexpr size_t get_num_arcs() const noexcept
Return the number of arcs of the graph.
Definition graph-dry.H:1064
Node * get_tgt_node(Arc *arc) const noexcept
Return the target node of arc (only for directed graphs)
Definition graph-dry.H:1023
static void map_nodes(N1 *p, N2 *q) noexcept
Map the nodes through their cookies.
Definition graph-dry.H:1281
PredicateWith<F, Args...>, and neither the call nor the conversion of its result to bool can throw.
DynArray< Graph::Arc * > arcs
Definition graphpic.C:408
#define ARC_COOKIE(p)
Return the arc cookie
#define NODE_COUNTER(p)
Get the counter of a node.
#define ARC_BITS(p)
Return the control bits of arc p.
#define NODE_COOKIE(p)
Return the node cookie
void clear_graph(GT &g)
Clean a graph: all its nodes and arcs are removed and freed.
Definition tpl_graph.H:4776
#define IS_ARC_VISITED(p, bit)
Determine whether the bit field is or not set to one.
#define NODE_BITS(p)
Get the control bits of a node.
@ Spanning_Tree
Definition aleph-graph.H:79
FFT< double > F
Main namespace for Aleph-w library functions.
void timsort(T *a, const size_t n, const Compare &cmp=Compare())
Timsort — adaptive, stable, natural merge sort.
and
Check uniqueness with explicit hash + equality functors.
Filtered iterator on all the arcs of a graph.
Definition tpl_graph.H:1200
Default filter for filtered iterators on arcs.
Definition tpl_graph.H:1024
Comparison functor for arc weights/distances.
Helper struct for initializing node counters during DFS.
Definition Kruskal.H:101
void operator()(const GT &, typename GT::Node *p) noexcept
Definition Kruskal.H:106
Filter for arcs painted by Kruskal's algorithm.
Definition Kruskal.H:139
bool operator()(typename G::Arc *a) const noexcept(NothrowPredicateWith< GT_SA &, typename G::Arc *& >)
Whether the filter of the caller shows a and a is painted as an arc of the spanning tree.
Definition Kruskal.H:153
Distance accessor.
size_t V
static int * k
Array-based graph implementation.
Dynamic array container with automatic resizing.
Utility algorithms and operations for graphs.
Comprehensive sorting algorithms and search utilities for Aleph-w.
DAG (acyclic) graph testing.
Union-Find (Disjoint Set Union) data structure.