Skip to content

Commit 883a6d9

Browse files
authored
C++ implementation of TARJAN's algorithm for topological sorting
1 parent 20e9877 commit 883a6d9

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
//Prints the Lexicographically smallest TS order.
2+
#include <bits/stdc++.h>
3+
using namespace std;
4+
#define endl '\n'
5+
vector< vector<int> > v(100);
6+
vector<bool> visit(100,false);
7+
stack<int> st;
8+
void toposort(int s)
9+
{
10+
visit[s]=true;
11+
for(int i=0;i<v[s].size();i++)
12+
{
13+
if(visit[v[s][i]]==false)
14+
{
15+
toposort(v[s][i]);
16+
}
17+
}
18+
st.push(s);
19+
}
20+
int main()
21+
{
22+
ios_base::sync_with_stdio(false);
23+
cin.tie(NULL);
24+
int n,m;
25+
cin>>n>>m;
26+
while(m--)
27+
{
28+
int x,y;
29+
cin>>x>>y;
30+
v[x].push_back(y);
31+
}
32+
for(int i=1;i<=n;i++)
33+
sort(v[i].rbegin(),v[i].rend());
34+
for(int i=n;i>=1;i--)
35+
if(visit[i]==false)
36+
toposort(i);
37+
while(!st.empty())
38+
{
39+
cout<<st.top()<<" ";
40+
st.pop();
41+
}
42+
return 0;
43+
}

0 commit comments

Comments
 (0)