forked from kothariji/competitive-programming
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCourse Schedule.cpp
89 lines (76 loc) · 1.56 KB
/
Course Schedule.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <bits/stdc++.h>
using namespace std;
#define int long long
bool isCyclePresent(int u, vector<int> adj[], vector<bool> &vis, vector<bool> &recStack)
{
vis[u] = true;
recStack[u] = true;
for(auto x:adj[u])
{
if(!vis[x] && isCyclePresent(x, adj, vis, recStack))
{
return true;
}
else if(recStack[x])
{
return true;
}
}
recStack[u] = false;
return false;
}
void dfs(int u, vector<int> adj[], vector<bool> &vis, stack<int>&st)
{
vis[u] = 1;
for(auto x:adj[u])
{
if(!vis[x])
{
dfs(x, adj, vis, st);
}
}
st.push(u);
}
signed main()
{
int n, m;
cin>>n>>m;
int inf = 1e18;
vector<int> adj1[n+1];
vector<int> adj2[n+1];
for(int i=0; i<m; i++)
{
int from, to;
cin>>from>>to;
adj1[from].push_back(to);
adj2[to].push_back(from);
}
vector<bool> vis1(n+1, false);
vector<bool> vis2(n+1, false);
vector<bool> recStack(n+1, false);
for(int i=1; i<=n; i++)
{
if(!vis1[i])
{
if(isCyclePresent(i, adj1, vis1, recStack))
{
cout<<"IMPOSSIBLE"<<endl;
return 0;
}
}
}
stack<int> st;
for(int i=1; i<=n; i++)
{
if(!vis2[i])
{
dfs(i, adj1, vis2, st);
}
}
while(!st.empty())
{
cout<<st.top()<<" ";
st.pop();
}
cout<<endl;
}