Problem:
A topological sort of a directed graph is an ordering of the vertices such that for every directed edge u → v, the vertex u comes before the vertex v in the order. Given a directed graph in DIMACS format, print the integer labels of the vertices, separated with spaces,in a topologically sorted order. If the graph contains a directed cycle, topological sorting is not possible. In this case, print the word cyclic. Example. The directed graph G in Fig. 1 is acyclic. One possible topological sort is given below.
3 2 4 1 5
The DIMACS graph format:
We use the textual DIMACS file format for representing graphs. The same format is used for both directed and undirected graphs. The file begins with a line of the form
p edge n m
where n ≥ 0 is the number of vertices and m ≥ 0 is the number of edges. The vertices are labeled with integers from 1 to n. This is followed by m lines describing the edges. Each such line has the form
e u v
where u and v are integers from 1 to n. This represents an edge joining vertices u and v. If the file represents a directed graph, the edge is directed from u to v.
Your programs should read these lines from a file whose name is given as a command line argument. You can assume that the input conforms to the format described above. It is not necessary to check syntax errors, but correct syntax must result in correct
output.
C Code:
A topological sort of a directed graph is an ordering of the vertices such that for every directed edge u → v, the vertex u comes before the vertex v in the order. Given a directed graph in DIMACS format, print the integer labels of the vertices, separated with spaces,in a topologically sorted order. If the graph contains a directed cycle, topological sorting is not possible. In this case, print the word cyclic. Example. The directed graph G in Fig. 1 is acyclic. One possible topological sort is given below.
3 2 4 1 5
The DIMACS graph format:
We use the textual DIMACS file format for representing graphs. The same format is used for both directed and undirected graphs. The file begins with a line of the form
p edge n m
where n ≥ 0 is the number of vertices and m ≥ 0 is the number of edges. The vertices are labeled with integers from 1 to n. This is followed by m lines describing the edges. Each such line has the form
e u v
where u and v are integers from 1 to n. This represents an edge joining vertices u and v. If the file represents a directed graph, the edge is directed from u to v.
Your programs should read these lines from a file whose name is given as a command line argument. You can assume that the input conforms to the format described above. It is not necessary to check syntax errors, but correct syntax must result in correct
output.
C Code: