Write a C++ program called ts.cpp that implements the topological sorting algori
ID: 3738455 • Letter: W
Question
Write a C++ program called ts.cpp that implements the topological sorting algorithm based on the DFS algorithm. Your program should read an input file name and determine if the input graph is a DAG (-directed acyclic graph) or not. If the graph is not a DAG, your program has to stop without further processing. However, if it's a DAG, your program should display the starting nodefs), popping-off order, and topologically sorted list. In the problem, you can assume that the number of nodes in the input file is less than 100. When we grade your programming assignment, we will use the g++ compiler on the cloud9. So, you must use the cloud9 for the homework. Additionally, you must include five items such as "Title", "Abstract", Class ID", "Name", and "Date"at the beginning of the program as head comments Input file format: This is a sample input file called t1.txt. The first line (= 3 in the example) indicates that there are three vertices in the graph. The second line ( in the example) presents the number of edges in the graph. The remaining two lines are the edge information in the graph. For the homework, you should assume that the first vertex starts from the number 0. Thus, tl.txt describes a directed graph like below: $ gt+ -o sa ts-cpp Enter a filename : ?:1 mpWt1.txt This is a DAG Start node (s): 0 Popping-off order: 21 0 Topological sort: 0->> 2 In the program, your program has to follow our convention ( ascending order) as you learned in theExplanation / Answer
SOurceCode:
#include <iostream>
#include <string>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
int main()
{
char filename[50];
int i,j,k,n,a[10][10],indeg[10],flag[10],count=0;
FILE *fp;
cout<<"Enter filename: ";
cin>> filename;
fp = fopen(filename, "r");
if (fp == NULL)
{
cout << "You entered incorrect filename." << endl;
return 0;
}
fscanf (fp, "%d", &n);
for(i=0;i<n;i++)
{
for (j = 0; j < n; j++)
{
fscanf (fp, "%d", &a[i][j]);
}
}
for(i=0;i<n;i++)
{
indeg[i]=0;
flag[i]=0;
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
indeg[i]=indeg[i]+a[j][i];
}
}
cout<<" Topological sort: ";
cout << "0";
while(count<n)
{
for(k=0;k<n;k++)
{
if((indeg[k]==0) && (flag[k]==0))
{
cout << " -> "<< k;
flag[k]=1;
}
for(i=0;i<n;i++)
{
if(a[i][k]==1)
{
indeg[k]--;
}
}
}
count++;
}
cout << endl;
return 0;
}
Output:
Enter filename: t1.txt
Topological sort: 0 -> 0 -> 1 -> 2 -> 3 -> 4
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.