-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtopologicalSort.cpp
More file actions
49 lines (44 loc) · 1.05 KB
/
Copy pathtopologicalSort.cpp
File metadata and controls
49 lines (44 loc) · 1.05 KB
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
#include <bits/stdc++.h>
using namespace std;
void topologicalSortUtil(vector<int> Graph[], int V, bool Visited[], stack<int> &Stack, int i)
{
Visited[i] = true;
int n = Graph[i].size();
for (int j = 0; j < n; ++j)
if (!Visited[Graph[i][j]])
topologicalSortUtil(Graph, V, Visited, Stack, Graph[i][j]);
Stack.push(i);
}
void topologicalSort(vector<int> Graph[], int V)
{
bool Visited[V] = {false};
stack<int> Stack;
for (int i = 0; i < V; ++i)
if (!Visited[i])
topologicalSortUtil(Graph, V, Visited, Stack, i);
while (!Stack.empty())
{
cout << Stack.top() << " ";
Stack.pop();
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int V, E;
cin >> V >> E;
vector<int> Graph[V];
for (int i = 0; i < E; ++i)
{
int s, d;
cin >> s >> d;
Graph[s].push_back(d);
}
topologicalSort(Graph, V);
return 0;
}