-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathTopological sort_dfs.cpp
More file actions
57 lines (50 loc) · 968 Bytes
/
Copy pathTopological sort_dfs.cpp
File metadata and controls
57 lines (50 loc) · 968 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
//https://cses.fi/problemset/task/1679/
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
vector<int> vis;
stack<int> s;
vector<vector<int>> adj;
void dfs(int u)
{
vis[u]=1;
for(auto v:adj[u])
{
if(!vis[v])
dfs(v);
else if(vis[v]==1)
{
cout << "IMPOSSIBLE\n";//if a node is visited,and that node is not is stack(i.e vis!=2) then the graph is cyclic
exit(0);
}
}
vis[u]=2;
s.push(u);
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n, m;
cin >> n >> m;
adj.assign(n + 1, {});
vis.assign(n + 1, 0);
for (int i = 0; i < m; i++)
{
int x,y;
cin >> x >> y;
adj[x].push_back(y);
}
for(int i=1;i<=n;i++)
{
if(!vis[i])
dfs(i);
}
while(!s.empty())
{
cout << s.top() << " ";
s.pop();
}
return 0;
}