Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
topological_sort.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
53#ifndef TOPOLOGICAL_SORT_H
54#define TOPOLOGICAL_SORT_H
55
56# include <ah-graph-concepts.H>
57
58#include <tpl_dfs_stack.H>
59#include <tpl_dynListQueue.H>
60#include <tpl_graph.H>
61
62namespace Aleph {
63
79template <AlephGraph GT,
80 template <typename, class> class Itor = Out_Iterator,
81 ArcFilter<GT> SA = Dft_Show_Arc<GT>>
83{
85 const GT * gptr;
86
87public:
88
92 Topological_Sort(SA && __sa = SA())
93 : sa(std::move(__sa)), gptr(nullptr) { /* empty */ }
94
99 : sa(__sa), gptr(nullptr) { /* empty */ }
100
101private:
102
103 // A node that waits for the one that it visits, and the next of its
104 // arcs to look at
105 struct Frame
106 {
107 typename GT::Node * curr;
108 Itor<GT, SA> it;
109
110 [[gnu::always_inline]] ALEPH_FLATTEN
111 Frame(typename GT::Node * p, SA & sa) : curr(p), it(p, sa) {}
112
113 [[gnu::always_inline]] ALEPH_FLATTEN
114 void next_arc() noexcept(noexcept(it.next_ne())) { it.next_ne(); }
115
116 // Moves the iterator to the next arc whose target was not visited, and
117 // gives that target; nullptr when the arcs are done
118 [[gnu::always_inline]] ALEPH_FLATTEN
120 {
121 for (; it.has_curr(); it.next_ne())
122 if (auto tgt = it.get_tgt_node_ne(); not IS_NODE_VISITED(tgt, Depth_First))
123 return tgt;
124 return nullptr;
125 }
126 };
127
137 template <template <class> class List>
138 size_t topological_sort(typename GT::Node * curr,
140 {
141 assert(gptr != nullptr);
142
143 if (IS_NODE_VISITED(curr, Depth_First))
144 return 0;
145
146 NODE_BITS(curr).set_bit(Depth_First, 1); // mark as visited
147
148 // visit adjacent nodes in postfix order
149 size_t inserted = 0;
150 Dfs_Stack<Frame> frames;
151 Frame * f = &frames.push(curr, sa); // the top one
152 while (true)
153 {
154 if (auto tgt = f->next_target())
155 { // the iterator stays on the arc to tgt, as in a recursion
156 NODE_BITS(tgt).set_bit(Depth_First, 1);
157 f = &frames.push(tgt, sa);
158 continue;
159 }
160
161 list.insert(f->curr); // postfix insertion of node that became a sink
162 ++inserted;
163 frames.pop();
164 if (frames.is_empty())
165 return inserted;
166
167 f = &frames.top();
168 f->next_arc(); // past the arc to the node that was visited
169 }
170 }
171
172public:
173
188 template <template <class> class List>
189 [[nodiscard]] List<typename GT::Node*> perform(const GT & g)
190 {
191 g.reset_bit_nodes(Depth_First); // initialize visit marks
192
193 gptr = &g;
195
196 // traverse all nodes, until every one is in the list
197 const auto & n = gptr->get_num_nodes();
198 size_t listed = 0;
199 for (auto it = g.get_node_it(); it.has_curr() and listed < n;
200 it.next_ne())
201 {
202 auto curr = it.get_current_node_ne();
203 if (not IS_NODE_VISITED(curr, Depth_First))
204 listed += topological_sort(curr, list);
205 }
206
207 return list;
208 }
209
215 {
216 perform<DynDlist>(g).swap(list);
217 }
218};
219
239template <AlephGraph GT,
240 template <typename, class> class Itor = Out_Iterator,
241 ArcFilter<GT> SA = Dft_Show_Arc<GT>>
243{
245
246public:
247
251 Q_Topological_Sort(SA && __sa = SA())
252 : sa(std::move(__sa)) { /* empty */ }
253
258 : sa(__sa) { /* empty */ }
259
275 template <template <class> class List>
276 [[nodiscard]] List<typename GT::Node*> perform(const GT & g)
277 {
279
281
282 // traverse all arcs and count in-degrees
283 for (Arc_Iterator<GT,SA> it(g, sa); it.has_curr(); it.next_ne())
284 NODE_COUNTER(it.get_tgt_node_ne())++;
285
286 // find nodes with in-degree 0 and enqueue them
287 DynListQueue<typename GT::Node*> q; // queue of sources
288 for (auto it = g.get_node_it(); it.has_curr(); it.next_ne())
289 {
290 auto p = it.get_current_node_ne();
291 if (NODE_COUNTER(p) == 0) // is it a source node?
292 q.put(p); // yes => enqueue it
293 }
294
295 while (not q.is_empty())
296 {
297 auto p = q.get(); // dequeue last source
298
299 assert(NODE_COUNTER(p) == 0);
300
301 list.append(p); // insert in topological order
302
303 // decrement in-degree of each node adjacent to p
304 for (Itor<GT, SA> it(p, sa); it.has_curr(); it.next_ne())
305 {
306 auto tgt = it.get_tgt_node_ne();
307 if (--NODE_COUNTER(tgt) == 0) // does tgt become a source?
308 q.put(tgt); // yes => enqueue it
309 }
310 }
311
312 return list;
313 }
314
332 template <template <class> class RankList = DynList,
333 template <class> class List = DynList>
334 [[nodiscard]] RankList<List<typename GT::Node*>> ranks(const GT & g)
335 {
337
338 // traverse all nodes to count in-degrees
339 for (typename GT::Node_Iterator i(g); i.has_curr(); i.next_ne())
340 for (Itor<GT, SA> j(i.get_current_node_ne(), sa);
341 j.has_curr(); j.next_ne())
342 NODE_COUNTER(j.get_tgt_node())++;
343
344 // find nodes with in-degree 0 and enqueue them
345 DynListQueue<typename GT::Node*> q; // queue of sources
346 for (typename GT::Node_Iterator it(g); it.has_curr(); it.next_ne())
347 {
348 auto p = it.get_current_node_ne();
349 if (NODE_COUNTER(p) == 0) // is it a source node?
350 q.put(p); // yes => enqueue it
351 }
352
353 RankList<List<typename GT::Node*>> ranks; // return value
354 while (not q.is_empty())
355 {
358
359 while (not q.is_empty()) // extract all nodes at level i
360 {
361 auto p = q.get(); // dequeue last source
362 rank.append(p); // insert in current rank
363
364 // decrement in-degree of each node adjacent to p
365 for (Itor<GT, SA> it(p, sa); it.has_curr(); it.next_ne())
366 {
367 auto tgt = it.get_tgt_node_ne();
368 if (--NODE_COUNTER(tgt) == 0) // does tgt become a source?
369 aq.put(tgt); // yes => enqueue in auxiliary queue
370 }
371 }
372
373 ranks.append(std::move(rank));
374 q.swap(aq);
375 assert(aq.is_empty());
376 }
377
378 return ranks;
379 }
380
386 {
387 auto result = this->ranks<>(g);
388 list.empty();
389 for (auto it = result.get_it(); it.has_curr(); it.next_ne())
390 list.append(std::move(it.get_curr()));
391 }
392
398 {
399 this->ranks<DynList>(g).swap(list);
400 }
401
407 {
408 this->perform<DynDlist>(g).swap(list);
409 }
410};
411
412} // end namespace Aleph
413
414#endif // TOPOLOGICAL_SORT_H
C++20 concepts for the protocol shared by graph algorithms.
List_Graph< Graph_Node< Node_Info >, Graph_Arc< Arc_Info > > GT
Stack of the frames of a depth-first search that does not recurse.
T & push(Args &&...args)
Builds a frame on top of the stack.
bool is_empty() const noexcept
Whether the stack has no frames.
T & top() noexcept
The top frame; the stack must not be empty.
void pop() noexcept
Destroys the top frame; the stack must not be empty.
Node belonging to a double circular linked list with header node.
Definition tpl_dnode.H:106
Dynamic doubly linked list with O(1) size and bidirectional access.
Dynamic queue of elements of generic type T based on single linked list.
T & put(const T &data)
The type of element.
T get()
Remove the oldest item of the queue.
void swap(DynListQueue &__q) noexcept
Swap this with __q in constant time.
bool is_empty() const noexcept
Return true if this is empty.
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
void next_ne() noexcept(shows_ne)
Advances the iterator to the next filtered element, as next() does.
A filter that an algorithm object keeps: one given as an lvalue is used where it is,...
Definition tpl_graph.H:1249
Filtered iterator for outcoming arcs of a node.
Definition tpl_graph.H:1942
Computes topological ordering using breadth-first search (Kahn's algorithm).
void operator()(const GT &g, DynList< DynList< typename GT::Node * > > &list)
Operator() overload returning ranks as DynList of DynList.
Q_Topological_Sort(SA &&__sa=SA())
Constructor with rvalue arc filter.
Q_Topological_Sort(SA &__sa)
Constructor with lvalue arc filter.
void operator()(const GT &g, DynDlist< typename GT::Node * > &list)
Operator() overload for backward compatibility (flat list).
void operator()(const GT &g, DynDlist< DynList< typename GT::Node * > > &list)
Operator() overload returning ranks as DynDlist of DynList.
List< typename GT::Node * > perform(const GT &g)
Compute topological ordering using BFS (Kahn's algorithm).
RankList< List< typename GT::Node * > > ranks(const GT &g)
Compute rank-based topological ordering.
Computes topological ordering using depth-first search.
List< typename GT::Node * > perform(const GT &g)
Compute topological ordering using DFS.
Topological_Sort(SA &&__sa=SA())
Constructor with rvalue arc filter.
void operator()(const GT &g, DynDlist< typename GT::Node * > &list)
Operator() overload for backward compatibility.
Topological_Sort(SA &__sa)
Constructor with lvalue arc filter.
size_t topological_sort(typename GT::Node *curr, List< typename GT::Node * > &list)
Helper for DFS-based topological sort.
void reset_bit_nodes(int bit) const noexcept
Reset bit to zero for all the nodes of graph.
Definition graph-dry.H:1326
constexpr size_t get_num_nodes() const noexcept
Return the total of nodes of graph.
Definition graph-dry.H:975
void reset_counter_nodes() const noexcept
Reset all the counters to zero for all the nodes of graph.
Definition graph-dry.H:1350
auto get_node_it() const noexcept
Obtains an iterator to the nodes of graph.
Definition graph-dry.H:3122
#define NODE_COUNTER(p)
Get the counter of a node.
#define IS_NODE_VISITED(p, bit)
Determine whether the control bit is set or not to one.
#define NODE_BITS(p)
Get the control bits of a node.
#define ALEPH_FLATTEN
[[gnu::flatten]], or nothing where it would only make the compilation slower.
@ Depth_First
Definition aleph-graph.H:73
Main namespace for Aleph-w library functions.
and
Check uniqueness with explicit hash + equality functors.
void next_ne() noexcept(noexcept(std::declval< Aleph::const_iterator_t< HeadC > & >().next_ne()) and noexcept(std::declval< ZipIterator< TailC... > & >().next_ne()))
Advance all underlying iterators (unchecked variant).
Definition ah-zip.H:252
STL namespace.
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
void next_arc() noexcept(noexcept(it.next_ne()))
Frame(typename GT::Node *p, SA &sa)
Stack of the frames of a depth-first search that does not recurse.
Dynamic queue implementation based on linked lists.
Generic graph and digraph implementations.