CSES - Shared codeLink to this code:
https://cses.fi/paste/a91f59b9d7a1d0f3770c5f/
#include<iostream>
#include<vector>
#include<stack>
#define REP(i, N) for(int i = 0;i < N;++i)
using namespace std;
int main() {
int N, M;
cin >> N >> M;
vector< vector<int> > A(N + 1);
vector<int> in(N + 1);
int a, b;
REP(i, M) {
cin >> a >> b;
A[a].push_back(b);
++in[b];
}
stack<int> s;
for (int i = 1;i < N + 1;++i) {
if (!in[i]) s.push(i);
}
vector<int> topological;
while (!s.empty()) {
int u = s.top();
s.pop();
topological.push_back(u);
for (int v : A[u]) {
--in[v];
if (!in[v]) s.push(v);
}
}
if (topological.size() < N) {
cout << "IMPOSSIBLE" << endl;
return 0;
}
for (int a : topological) {
cout << a << ' ';
}
cout << endl;
}