Problem Statement
Course Schedule
Implementation
void solve() {
ll n, m;
cin >> n >> m;
vvll v(n);
rep(i, m) {
ll x, y;
cin >> x >> y;
--x, --y;
v[x].pb(y);
}
vll col(n, 0), p(n, 0), topo;
function <bool(ll, ll)> dfs = [&](ll node, ll pr) {
col[node] = 1, p[node] = pr;
for (auto& child : v[node]) {
if (col[child] == 0) {
if (dfs(child, node)) return 1;
}
else if (col[child] == 1) {
return 1;
}
}
col[node] = 2;
topo.pb(node);
return 0;
};
rep(i, n) {
if (col[i] == 0) {
if (dfs(i, i)) {
cout << "IMPOSSIBLE\n";
return;
}
}
}
reverse(all(topo));
for (auto& x : topo) cout << x + 1 << " ";
cout << "\n";
}