-
Notifications
You must be signed in to change notification settings - Fork 2
/
TopologicalSorting.cpp
74 lines (68 loc) · 962 Bytes
/
TopologicalSorting.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include "bits/stdc++.h"
using namespace std;
#define N 10000
vector<int> graph[N], topo;
bool visited[N];
stack<int> S;
inline void dfs(int node)
{
visited[node]=true;
if(graph[node].size()==0)
{
S.push(node);
return;
}
for(int i=0;i<graph[node].size();i++)
{
int v=graph[node][i];
if(!visited[v])
{
dfs(v);
}
}
bool nomore=false;
for(int i=0;i<graph[node].size();i++)
{
int v=graph[node][i];
if(visited[v]==false)
{
nomore=1;
}
}
if(!nomore)
{
S.push(node);
}
}
int main()
{
int vertices,edges,i,j;
cin >> vertices;
cin >> edges;
for(i=0;i < edges;i++)
{
// directed from u->v
int u,v;
cin >> u >> v;
graph[u].push_back(v);
}
memset(visited,0,sizeof(visited));
for(i=1;i <= vertices;i++)
{
if(visited[i]==false)
{
dfs(i);
}
}
while(!S.empty())
{
topo.push_back(S.top());
S.pop();
}
for(i=topo.size()-1;i >=0 ;i--)
{
cout << topo[i] << " ";
}
cout << "\n";
return 0;
}