200#include <unordered_map>
201#include <unordered_set>
204#include <tclap/CmdLine.h>
207using namespace Aleph;
216bool verify_topological_order(
const TaskGraph & g,
218 std::vector<TaskGraph::Node*> * missing_nodes =
nullptr)
220 std::unordered_map<TaskGraph::Node*, size_t> pos;
221 pos.reserve(order.
size());
224 for (
auto it = order.
get_it(); it.has_curr(); it.next(), ++i)
225 pos.emplace(it.get_curr(), i);
227 if (missing_nodes !=
nullptr)
229 missing_nodes->clear();
230 missing_nodes->reserve(g.get_num_nodes());
231 for (
auto nit = g.get_node_it(); nit.has_curr(); nit.next_ne())
233 auto * n = nit.get_curr();
234 if (pos.find(n) == pos.end())
235 missing_nodes->push_back(n);
239 for (
auto ait = g.get_arc_it(); ait.has_curr(); ait.next_ne())
241 auto * a = ait.get_curr();
242 auto * u = g.get_src_node(a);
243 auto * v = g.get_tgt_node(a);
245 const auto it_u = pos.find(u);
246 const auto it_v = pos.find(v);
247 if (it_u == pos.end() || it_v == pos.end())
250 if (it_u->second >= it_v->second)
257void print_missing_nodes(
const std::vector<TaskGraph::Node*> & missing)
262 cout <<
"Missing nodes (not produced by the algorithm): ";
264 for (
auto * n : missing)
266 if (!first) cout <<
", ";
267 cout << n->get_info();
297 auto config_h = g.insert_node(
"config.h");
298 auto utils_h = g.insert_node(
"utils.h");
301 auto utils_o = g.insert_node(
"utils.o");
302 auto parser_o = g.insert_node(
"parser.o");
303 auto lexer_o = g.insert_node(
"lexer.o");
304 auto main_o = g.insert_node(
"main.o");
305 auto test_o = g.insert_node(
"test.o");
308 auto program = g.insert_node(
"program");
309 auto test_suite = g.insert_node(
"test_suite");
312 g.insert_arc(config_h, utils_h);
313 g.insert_arc(config_h, parser_o);
314 g.insert_arc(utils_h, utils_o);
315 g.insert_arc(utils_h, lexer_o);
316 g.insert_arc(utils_o, main_o);
317 g.insert_arc(utils_o, test_o);
318 g.insert_arc(parser_o, main_o);
319 g.insert_arc(lexer_o, parser_o);
320 g.insert_arc(lexer_o, test_o);
321 g.insert_arc(main_o, program);
322 g.insert_arc(test_o, test_suite);
345 auto math101 = g.insert_node(
"Math101");
346 auto math201 = g.insert_node(
"Math201");
347 auto math301 = g.insert_node(
"Math301");
350 auto cs101 = g.insert_node(
"CS101");
351 auto cs102 = g.insert_node(
"CS102");
352 auto cs201 = g.insert_node(
"CS201");
353 auto cs301 = g.insert_node(
"CS301");
354 auto cs302 = g.insert_node(
"CS302");
357 g.insert_arc(math101, math201);
358 g.insert_arc(math201, math301);
359 g.insert_arc(math101, cs101);
360 g.insert_arc(cs101, cs102);
361 g.insert_arc(cs101, cs201);
362 g.insert_arc(math201, cs201);
363 g.insert_arc(cs201, cs301);
364 g.insert_arc(cs301, cs302);
365 g.insert_arc(cs102, cs302);
375 for (
auto it = g.get_node_it(); it.has_curr(); it.next())
376 if (it.get_curr()->get_info() == name)
377 return it.get_curr();
386 cout <<
"\n=== " << title <<
" ===" << endl;
387 cout <<
"Tasks: " << g.get_num_nodes() << endl;
388 cout <<
"Dependencies: " << g.get_num_arcs() << endl;
390 cout <<
"\nDependency structure:" << endl;
391 for (
auto nit = g.get_node_it(); nit.has_curr(); nit.next())
393 auto* node = nit.get_curr();
394 cout <<
" " << node->get_info() <<
" depends on: ";
398 for (
auto ait = g.get_arc_it(); ait.has_curr(); ait.next())
400 auto* arc = ait.get_curr();
401 if (g.get_tgt_node(arc) == node)
403 if (not first) cout <<
", ";
404 cout << g.get_src_node(arc)->get_info();
408 if (first) cout <<
"(none - root task)";
418 cout <<
"\n--- DFS-based Topological Sort ---" << endl;
419 cout <<
"Algorithm: Post-order DFS traversal" << endl;
426 cout <<
"\nExecution order:" << endl;
428 for (
auto it = sorted.
get_it(); it.has_curr(); it.next(), ++step)
430 auto* node = it.get_curr();
431 cout <<
" " << setw(2) << step <<
". " << node->get_info() << endl;
434 std::vector<TaskGraph::Node*> missing;
435 const bool ok = verify_topological_order(g, sorted, &missing);
438 cout <<
"\n[Warning] The produced order is not a valid topological ordering.\n";
439 cout <<
"This usually means the input graph is not a DAG (has a cycle) or the order is incomplete.\n";
440 print_missing_nodes(missing);
446 cout <<
"\nVerification: Each task appears after all its dependencies." << endl;
455 cout <<
"\n--- BFS-based Topological Sort (Kahn's Algorithm) ---" << endl;
456 cout <<
"Algorithm: Iteratively remove source nodes (in-degree 0)" << endl;
463 cout <<
"\nExecution order:" << endl;
465 for (
auto it = sorted.
get_it(); it.has_curr(); it.next(), ++step)
467 auto* node = it.get_curr();
468 cout <<
" " << setw(2) << step <<
". " << node->get_info() << endl;
471 std::vector<TaskGraph::Node*> missing;
472 const bool ok = verify_topological_order(g, sorted, &missing);
475 cout <<
"\n[Warning] Kahn's algorithm did not produce a complete valid ordering.\n";
476 cout <<
"If output size < V, the graph contains a cycle (not a DAG).\n";
477 print_missing_nodes(missing);
483 cout <<
"\nParallel execution ranks:" << endl;
489 std::unordered_set<TaskGraph::Node*> seen;
490 seen.reserve(g.get_num_nodes());
491 for (
auto rit =
ranks.
get_it(); rit.has_curr(); rit.next_ne())
492 for (
auto nit = rit.get_curr().get_it(); nit.has_curr(); nit.next_ne())
494 auto * n = nit.get_curr();
495 if (seen.insert(n).second)
498 std::vector<TaskGraph::Node*> missing_ranks;
499 const bool ok_ranks = verify_topological_order(g, flat, &missing_ranks);
502 cout <<
"\n[Warning] Rank-based output is incomplete/invalid (cycle or missing nodes).\n";
503 print_missing_nodes(missing_ranks);
507 for (
auto rit =
ranks.
get_it(); rit.has_curr(); rit.next(), ++rank_num)
509 cout <<
" Level " << rank_num <<
" (can run in parallel): ";
510 auto& rank = rit.get_curr();
512 for (
auto nit = rank.get_it(); nit.has_curr(); nit.next())
514 if (not first) cout <<
", ";
515 cout << nit.get_curr()->get_info();
528 cout <<
"\n" << string(60,
'=') << endl;
529 cout <<
"Example: Build System Dependencies" << endl;
530 cout << string(60,
'=') << endl;
535 cout <<
"\n--- Computing Build Order ---" << endl;
540 sorter(g, build_order);
542 cout <<
"\nBuild order (satisfies all dependencies):" << endl;
545 for (
auto it = build_order.
get_it(); it.has_curr(); it.next())
547 if (not first) cout <<
" && make ";
548 cout << it.get_curr()->get_info();
559 cout <<
"\n" << string(60,
'=') << endl;
560 cout <<
"Example: University Course Prerequisites" << endl;
561 cout << string(60,
'=') << endl;
566 cout <<
"\n--- Computing Course Order ---" << endl;
569 auto semesters = sorter.
ranks(g);
571 cout <<
"\nSuggested course schedule:" << endl;
573 for (
auto sit = semesters.get_it(); sit.has_curr(); sit.next(), ++semester)
575 cout <<
" Semester " << semester <<
": ";
576 auto& courses = sit.get_curr();
578 for (
auto cit = courses.get_it(); cit.has_curr(); cit.next())
580 if (not first) cout <<
", ";
581 cout << cit.get_curr()->get_info();
587 cout <<
"\nTotal semesters needed: " << (semester - 1) << endl;
590int main(
int argc,
char* argv[])
594 TCLAP::CmdLine
cmd(
"Topological Sort Example",
' ',
"1.0");
596 TCLAP::SwitchArg buildArg(
"b",
"build",
597 "Show build system example",
false);
598 TCLAP::SwitchArg courseArg(
"c",
"courses",
599 "Show course scheduling example",
false);
600 TCLAP::SwitchArg allArg(
"a",
"all",
601 "Run all demos",
false);
602 TCLAP::SwitchArg verboseArg(
"v",
"verbose",
603 "Show detailed output",
false);
610 cmd.parse(argc, argv);
612 bool runBuild = buildArg.getValue();
613 bool runCourse = courseArg.getValue();
614 bool runAll = allArg.getValue();
615 bool verbose = verboseArg.getValue();
617 if (not runBuild
and not runCourse)
620 cout <<
"=== Topological Sort: Task Ordering with Dependencies ===" << endl;
622 if (runAll or runBuild)
632 if (runAll or runCourse)
635 cout <<
"\n=== Algorithm Summary ===" << endl;
636 cout <<
"DFS-based: O(V + E), post-order traversal" << endl;
637 cout <<
"BFS-based: O(V + E), Kahn's algorithm (removes sources)" << endl;
638 cout <<
"Requirement: Input must be a DAG (no cycles)" << endl;
642 catch (TCLAP::ArgException& e)
644 cerr <<
"Error: " << e.error() <<
" for arg " << e.argId() << endl;
Generic directed graph (digraph) wrapper template.
typename BaseGraph::Node Node
Dynamic doubly linked list with O(1) size and bidirectional access.
const size_t & size() const noexcept
Return the number of elements (constant time)
T & append(const T &item)
Append a copied item at the end of the list.
Computes topological ordering using breadth-first search (Kahn's algorithm).
RankList< List< typename GT::Node * > > ranks(const GT &g)
Compute rank-based topological ordering.
Computes topological ordering using depth-first search.
auto get_it()
Return a properly initialized iterator positioned at the first item on the container.
Main namespace for Aleph-w library functions.
and
Check uniqueness with explicit hash + equality functors.
Array< size_t > ranks(const Array< T > &array)
Computes the rank of each element in an Array.
bool verbose
Flag enabling verbose output.
Arc of graph implemented with double-linked adjacency lists.
Node belonging to a graph implemented with a double linked adjacency list.
Topological sorting algorithms for directed acyclic graphs (DAGs).
void print_graph(TaskGraph &g, const string &title)
Print the graph structure.
TaskGraph build_courses_graph()
Build a course prerequisites graph.
void demo_build_order()
Demonstrate practical application: build order.
TaskGraph::Node * find_task(TaskGraph &g, const string &name)
Find a node by name.
TaskGraph build_project_graph()
Build a sample build system dependency graph.
void demo_course_scheduling()
Demonstrate practical application: course scheduling.
void demo_bfs_topological_sort(TaskGraph &g, bool verbose)
Demonstrate BFS-based topological sort (Kahn's algorithm)
void demo_dfs_topological_sort(TaskGraph &g, bool verbose)
Demonstrate DFS-based topological sort.
Generic graph and digraph implementations.