Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
Prim.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
90# ifndef PRIM_H
91# define PRIM_H
92
93# include <memory>
94
95# include <ah-graph-concepts.H>
96
97# include <tpl_agraph.H>
98# include <tpl_graph_utils.H>
99# include <archeap.H>
100# include <ah-errors.H>
101# include <cookie_guard.H>
102
103namespace Aleph
104{
105 using namespace Aleph;
106
107 template <AlephGraph GT>
109 {
110 typename GT::Node *tree_node = nullptr; // image in the spanning tree
111 void *heap_node = nullptr; // pointer into the dedicated heap
112
113 Prim_Info() : tree_node(nullptr), heap_node(nullptr)
114 { /* empty */
115 }
116 };
117
118# define PRIMINFO(p) static_cast<Prim_Info<GT>*>(NODE_COOKIE(p))
119# define TREENODE(p) (PRIMINFO(p)->tree_node)
120# define HEAPNODE(p) (PRIMINFO(p)->heap_node)
121
122 template <class GT, class Distance>
124 {
125 // Returns reference to the heap_node pointer stored in Prim_Info
126 // The actual type is determined by ArcHeap, but stored as void*
127 void *& operator ()(typename GT::Node *p)
128 {
129 return PRIMINFO(p)->heap_node;
130 }
131 };
132
133 template <class GT, class Distance>
135 {
136 // Returns reference to the cookie pointer used as heap node storage
137 void *& operator ()(typename GT::Node *p)
138 {
139 return NODE_COOKIE(p);
140 }
141 };
142
143 template <class GT>
145 {
147
148 Init_Prim_Info(GT & __tree) : tree(__tree)
149 { /* empty */
150 }
151
152 // Gives p its Prim_Info and its node in the tree, or, if creating either
153 // throws, leaves its cookie as it was
154 void operator ()(const GT & g, typename GT::Node *p)
155 {
157 auto info = std::make_unique<Prim_Info<GT>>();
158 info->tree_node = tree.insert_node(p->get_info());
159 NODE_COOKIE(p) = info.release();
160 }
161 };
162
163 template <AlephGraph GT>
165 {
166 void operator ()(const GT &, typename GT::Node *p)
167 {
168 const Prim_Info<GT> *aux = PRIMINFO(p);
169 // with aux still in its cookie, map_nodes() would chain aux to the
170 // node of the tree, which would then map back to freed memory
171 NODE_COOKIE(p) = nullptr;
172 GT::map_nodes(p, aux->tree_node);
173 delete aux;
174 }
175 };
176
177
219 template <AlephGraph GT,
220 class Distance = Dft_Dist<GT>,
221 ArcFilter<GT> SA = Dft_Show_Arc<GT>>
223 {
225
227
229
231
233 SA sa;
234
235 public:
241 Prim_Min_Spanning_Tree(Distance __dist = Distance(), SA __sa = SA())
242 : dist(__dist), sa(__sa)
243 {
244 // empty
245 }
246
247 private:
248 void paint_min_spanning_tree(const GT & g, typename GT::Node *first)
249 {
250 ah_domain_error_if(g.is_digraph()) << "g is a digraph";
251
252 g.reset_nodes();
253 g.reset_arcs();
254
255 NODE_BITS(first).set_bit(Aleph::Spanning_Tree, true); // visited
256
257 // The heap keeps its nodes in the cookies. If the distance throws,
258 // the heap frees the nodes it still has, so their cookies are cleared.
259 Scope_Guard cookies_guard(g, [](const GT & graph) {
260 for (typename GT::Node_Iterator it(graph); it.has_curr(); it.next_ne())
261 NODE_COOKIE(it.get_curr()) = nullptr;
262 });
263
265 for (Node_Arc_Iterator<GT, SA> it(first, sa); it.has_curr(); it.next_ne())
266 {
267 typename GT::Arc *arc = it.get_current_arc_ne();
268 typename GT::Node *tgt = it.get_tgt_node_ne();
270 continue; // a loop of first, which would close a cycle
271 heap.put_arc(arc, tgt);
272 }
273
274 const size_t V1 = g.get_num_nodes() - 1;
275 size_t count = 0;
276
277 while (count < V1 and not heap.is_empty())
278 { // get the next smallest arc
279 typename GT::Arc *min_arc = heap.get_min_arc();
281 continue;
282
283 typename GT::Node *src = g.get_src_node(min_arc);
284 typename GT::Node *tgt = g.get_tgt_node(min_arc);
287 continue; // this arc would close a cycle in the tree
288
289 typename GT::Node *tgt_node =
290 IS_NODE_VISITED(src, Aleph::Spanning_Tree) ? tgt : src;
291
292 ARC_BITS(min_arc).set_bit(Aleph::Spanning_Tree, true); // in the tree
293 NODE_BITS(tgt_node).set_bit(Aleph::Spanning_Tree, true);
294
295 // insert tgt_node's unvisited arcs into the heap
296 for (Node_Arc_Iterator<GT, SA> it(tgt_node, sa); it.has_curr();
297 it.next_ne())
298 {
299 typename GT::Arc *arc = it.get_current_arc_ne();
301 continue;
302
303 typename GT::Node *tgt = it.get_tgt_node_ne();
305 continue; // node visited ==> would cause a cycle
306
307 heap.put_arc(arc, tgt);
308 }
309
310 ++count;
311 }
312 }
313
314 void min_spanning_tree(const GT & g, typename GT::Node *first, GT & tree)
315 {
316 ah_domain_error_if(g.is_digraph()) << "g is a digraph";
317
318 clear_graph(tree);
319
320 // The first num_init nodes have a Prim_Info; if a later one cannot
321 // have its own, those are freed before the exception goes on
323 size_t num_init = 0;
324 try
325 {
326 for (Node_Iterator<GT> it(g); it.has_curr(); it.next_ne(), ++num_init)
327 init(g, it.get_curr());
328 }
329 catch (...)
330 {
331 for (Node_Iterator<GT> it(g); num_init > 0; it.next_ne(), --num_init)
332 {
333 delete PRIMINFO(it.get_curr());
334 NODE_COOKIE(it.get_curr()) = nullptr;
335 }
336 throw;
337 }
338 g.reset_arcs();
339
340 // Scope guard for exception safety - ensures Uninit is always called
341 Scope_Guard cleanup_guard(g, [](const GT & graph) {
343 });
344
345 NODE_BITS(first).set_bit(Aleph::Spanning_Tree, true); // visited
346
347 Heap heap(dist, Acc_Heap());
348 // insert the first node's initial arcs into the heap
349 for (Node_Arc_Iterator<GT, SA> it(first, sa); it.has_curr(); it.next_ne())
350 {
351 typename GT::Arc *arc = it.get_current_arc_ne();
352 typename GT::Node *tgt = it.get_tgt_node_ne();
354 continue; // a loop of first, which would close a cycle
355 heap.put_arc(arc, tgt);
356 }
357
358 const size_t V1 = g.get_num_nodes() - 1;
359
360 while (tree.get_num_arcs() < V1 and not heap.is_empty())
361 { // get the next smallest arc
362 typename GT::Arc *min_arc = heap.get_min_arc();
364 continue;
365
366 typename GT::Node *src = g.get_src_node(min_arc);
367 typename GT::Node *tgt = g.get_tgt_node(min_arc);
370 continue; // this arc would close a cycle in the tree
371
372 typename GT::Node *tgt_node =
373 IS_NODE_VISITED(src, Aleph::Spanning_Tree) ? tgt : src;
374
375 ARC_BITS(min_arc).set_bit(Aleph::Spanning_Tree, true); // in the tree
376 NODE_BITS(tgt_node).set_bit(Aleph::Spanning_Tree, true);
377
378 // insert tgt_node's unvisited arcs into the heap
379 for (Node_Arc_Iterator<GT, SA> it(tgt_node, sa); it.has_curr();
380 it.next_ne())
381 {
382 typename GT::Arc *arc = it.get_current_arc_ne();
384 continue;
385
386 typename GT::Node *tgt = it.get_tgt_node_ne();
388 continue; // node visited ==> would cause a cycle
389
390 heap.put_arc(arc, tgt);
391 }
392
393 // insert the new arc into tree and map it
394 typename GT::Arc *tree_arc =
395 tree.insert_arc(TREENODE(src), TREENODE(tgt), min_arc->get_info());
396 GT::map_arcs(min_arc, tree_arc);
397 }
398
399 // cleanup_guard destructor will call Uninit_Prim_Info for all nodes
400 }
401
402 public:
415 void operator ()(const GT & g, GT & tree)
416 {
417 min_spanning_tree(g, g.get_first_node(), tree);
418 }
419
433 void operator ()(const GT & g, typename GT::Node *start, GT & tree)
434 {
435 min_spanning_tree(g, start, tree);
436 }
437
439 void operator ()(const GT & g)
440 {
442 }
443
444 void operator ()(const GT & g, typename GT::Node *start)
445 {
446 paint_min_spanning_tree(g, start);
447 }
448 };
449
450
451# undef HEAPNODE
452# undef TREENODE
453# undef PRIMINFO
454} // end namespace Aleph
455
456# endif // PRIM_H
#define TREENODE(p)
Definition Dijkstra.H:136
#define PRIMINFO(p)
Definition Prim.H:118
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.
Arc heap for graph algorithms.
List_Graph< Graph_Node< Node_Info >, Graph_Arc< Arc_Info > > GT
Default distance accessor for arc weights.
void next_ne() noexcept(shows_ne)
Advances the iterator to the next filtered element, as next() does.
bool is_empty() const noexcept
Node * get_first_node() const
Return any node in the graph.
Definition tpl_graph.H:590
virtual Node * insert_node(Node *node) noexcept
Insertion of a node already allocated.
Definition tpl_graph.H:535
Arc * insert_arc(Node *src_node, Node *tgt_node, void *a)
Definition tpl_graph.H:618
Filtered iterator on the nodes of a graph.
Definition tpl_graph.H:1287
Functor that traverses the nodes of a graph and performs an operation.
Definition tpl_graph.H:3698
Computes the minimum spanning tree of a graph using Prim's algorithm.
Definition Prim.H:223
void paint_min_spanning_tree(const GT &g, typename GT::Node *first)
Definition Prim.H:248
void min_spanning_tree(const GT &g, typename GT::Node *first, GT &tree)
Definition Prim.H:314
Prim_Min_Spanning_Tree(Distance __dist=Distance(), SA __sa=SA())
Constructor.
Definition Prim.H:241
ArcHeap< GT, Distance, Acc_Simple_Heap > Simple_Heap
Definition Prim.H:230
ArcHeap< GT, Distance, Acc_Heap > Heap
Definition Prim.H:228
void operator()(const GT &g, GT &tree)
Invokes the computation of the minimum spanning tree using Prim's algorithm.
Definition Prim.H:415
Prim_Heap_Info< GT, Distance > Acc_Heap
Definition Prim.H:224
Simple_Prim_Heap< GT, Distance > Acc_Simple_Heap
Definition Prim.H:226
Generic RAII scope guard for cleanup operations on graphs.
void put_arc(typename GT::Arc *arc, typename GT::Node *tgt)
Insert or update an arc associated with a target node, keeping the smallest-distance arc per node in ...
Definition archeap.H:131
GT::Arc * get_min_arc()
Extract the arc with minimum distance from the heap and clear its node-to-heap mapping.
Definition archeap.H:171
ArcInfo & get_info() noexcept
Return a modifiable reference to the arc data.
Definition graph-dry.H:854
NodeInfo & get_info() noexcept
Return a modifiable reference to the data contained in the node.
Definition graph-dry.H:753
void reset_arcs() const
Reset all the arcs of graph (the control bits, the state, the counter and the cookie)
Definition graph-dry.H:1213
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(Node *node, int bit) const noexcept
Reset the bit of node (to zero)
Definition graph-dry.H:1087
constexpr size_t get_num_arcs() const noexcept
Return the number of arcs of the graph.
Definition graph-dry.H:1064
void reset_nodes() const
Reset all the nodes of graph (the control bits, the state, the counter and the cookie)
Definition graph-dry.H:1206
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
RAII guards for graph node/arc cookies.
#define IS_NODE_VISITED(p, bit)
Determine whether the control bit is set or not to one.
#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
Main namespace for Aleph-w library functions.
and
Check uniqueness with explicit hash + equality functors.
static std::atomic< bool > init
Definition hash-fct.C:54
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
Definition ahAlgo.H:127
Default filter for filtered iterators on arcs.
Definition tpl_graph.H:1024
void operator()(const GT &g, typename GT::Node *p)
Definition Prim.H:154
Init_Prim_Info(GT &__tree)
Definition Prim.H:148
Filtered iterator of adjacent arcs of a node.
Definition tpl_graph.H:1155
void *& operator()(typename GT::Node *p)
Definition Prim.H:127
void * heap_node
Definition Prim.H:111
GT::Node * tree_node
Definition Prim.H:110
void *& operator()(typename GT::Node *p)
Definition Prim.H:137
void operator()(const GT &, typename GT::Node *p)
Definition Prim.H:166
Distance accessor.
Array-based graph implementation.
Utility algorithms and operations for graphs.