-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtopologicalSort.cpp
More file actions
58 lines (54 loc) · 972 Bytes
/
topologicalSort.cpp
File metadata and controls
58 lines (54 loc) · 972 Bytes
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
#include <bits/stdc++.h>
using namespace std;
//TC-> O(N+E)
//SC-> O(N)+O(N)
void dfs(int node, stack<int> &st, vector<int> adj[], vector<int> &vis)
{
vis[node] = 1;
for (auto it : adj[node])
{
if (!vis[it])
{
dfs(it, st, adj, vis);
}
}
st.push(node);
}
vector<int> topoSort(int V, vector<int> adj[])
{
// code here
stack<int> st;
vector<int> vis(V, 0);
for (int i = 0; i < V; i++)
{
if (vis[i] == 0)
{
dfs(i, st, adj, vis);
}
}
vector<int> topo;
while (!st.empty())
{
topo.push_back(st.top());
st.pop();
}
return topo;
}
int main()
{
int n,m;
cin>>n>>m;
vector<int>adj[n];
for(int i=0;i<n;i++)
{
int u,v;
cin>>u>>v;
adj[u].push_back(v);
}
vector<int>ans = topoSort(n,adj);
for(int i=0;i<ans.size();i++)
{
cout<<ans[i]<<" ";
}
cout<<endl;
}