In what concerns the continuous evaluation solving exercises grade during the semester, you should submit until 23:59 of December 14th
(this exercise will still be available for submission after that deadline, but without couting towards your grade)
[to understand the context of this problem, you should read the class #09 exercise sheet]


[AED053] Topological Sorting

In this problem you should only submit a graph.h file with a self-containing definition of a class Graph.

Base Code

Use as a basis the class Graph (see code | download code) which implements a graph (that can have directions and weights) using an adjacency list, assumes nodes are identified by integers between 1 and |V| and already has methods for adding an edge, reading a graph and doing a basic DFS and a basic BFS.

The Problem

Add a new method std::list<int> topologicalSorting() to the class. If called on a directed graph withouth cycles, the function should return a vector containing a possible topological sorting, that is, an order of nodes in which node u comes before node v if and only if there is no edge (v,u). If there is more than one possible topological sorting, your answer could be any of those valid orders.

All the input graphs will be simple (no self-loops or parallel edges) and unweighted DAGs (that is, they will directed and acyclic). It is guaranteed that |V|<=100 and |E|<=500.

Submission

You should submit the file graph.h with the method topologicalSorting added to Graph as requested (and without removing any of the other existing methods). You can however create additional methods and/or attribute variables, if you need them.

Mooshak will use the following code to link to your class, read the inputs, build the graphs and call your method, printing its result.

#include <iostream>
#include <list>
#include "graph.h"

int main() {

  // Number of graphs to test
  int n;
  std::cin >> n;

  // For each graph: read, call the method and delete graph at the end
  for (int i=1; i<=n; i++) {
    Graph *g = Graph::readGraph();
    std::list<int> order = g->topologicalSorting();
    std::cout << "Graph #" << i << ":";
    for (int v : order) std::cout << " " << v;
    std::cout << std::endl;
    delete g;
  }
    
  return 0;
}

Example Input Example Output
2

9 directed unweighted
9
1 2
1 3
2 4
3 4
4 5
5 6
7 5
9 6
8 7

8 directed unweighted
8
3 1
1 2
2 4
5 4
4 6
6 7
6 8
8 7
Graph #1: 9 8 7 1 3 2 4 5 6
Graph #2: 5 3 1 2 4 6 8 7

Explanation of Example Input

The first graph of the example input corresponds to the following figure:

It has many possible topological orderings such has:

The second graph of the example input corresponds to the following figure:



Algorithms and Data Structures (L.EIC011) 2024/2025
DCC/FCUP & DEI/FEUP - University of Porto