Write a C++ program called ts.cpp that implements the topological sorting algori
ID: 3853326 • Letter: W
Question
Write a C++ program called ts.cpp that implements the topological sorting algorithm based on the source-removal algorithm. Your program should read an input file name. Then it should display the topological ordering. In the problem, you can assume that the number of vertices in the input file is less than 50. Additionally, you can assume that the input graph is always a DAG (= Directed Acyclic Graph). When you write the program, don’t forget to include “Title”, “Abstract”, “ID (A four-digit number)”, “Name”, and “Date”.
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. For the homework, we can assume that the first vertex starts from the number 0. Thus, t1.txt describes a directed graph like below:
One blank space is used to delimiter the data. Note that there’s no blank space at the end of each line. If your program does not read the file properly, your program will get no credit.
The following presents a sample run of the program. Your program should be compiled and executed exactly like this.
Enter filename: C:\tmp\t1.txt
Topological sort: 0 -> 1 -> 2
In the program, your program has to follow our convention (= ascending order).
This is another sample input file called t2.txt.
This is a sample run:
Enter filename: C:\tmp\t2.txt
Topological sort: 0 -> 1 -> 2 -> 3 -> 4
Again, your program must follow our convention (= ascending order). So, your program should remove the vertex 0 first between the two source vertices 0 and 1.
010 100 3000Explanation / Answer
#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
If this is helpful, do click on the thumbs up button. Thanks.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.