Link to this code:
https://cses.fi/paste/c8431ed4e67b8c202fc06d/#include<bits/stdc++.h>
using namespace std;
int main() {
// #ifndef ONLINE_JUDGE
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
// #endif
int n, m;
cin >> n >> m;
int id[n];
memset(id, 0, sizeof(id));
vector<vector<int>> adj(n);
for (int i = 0; i < m; i++) {
int x, y;
cin >> x >> y;
adj[x - 1].push_back(y - 1);
id[y - 1]++;
}
queue<int> q;
for (int i = 0; i < n; i++) {
if (id[i] == 0)
q.push(i);
}
vector<int> ans;
while (!q.empty()) {
ans.push_back(q.front());
for (int i = 0; i < adj[q.front()].size(); i++) {
id[adj[q.front()][i]]--;
if (id[adj[q.front()][i]] == 0) {
q.push(adj[q.front()][i]);
}
}
q.pop();
}
int sp[n];
sp[0] = 0;
for (int i = 1; i < n; i++)
sp[i] = INT_MAX;
int p[n];
for (int i = 0; i < n; i++)
p[i] = i;
int ind;
for (int i = 0; i < ans.size(); i++) {
if (ans[i] == 0) {
ind = i;
break;
}
}
for (int i = ind; i < ans.size(); i++) {
for (int j = 0; j < adj[ans[i]].size(); j++) {
if (sp[ans[i]] - 1 < sp[adj[ans[i]][j]]) {
sp[adj[ans[i]][j]] = sp[ans[i]];
p[adj[ans[i]][j]] = ans[i];
}
}
}
vector<int> a;
int i = n - 1;
while (p[i] != i && i != 0) {
a.push_back(i);
i = p[i];
}
a.push_back(i);
if ((*(a.end() - 1)) != 0)
cout << "IMPOSSIBLE" << endl;
else {
reverse(a.begin(), a.end());
cout << a.size() << endl;
for (int x : a)
cout << x + 1 << " ";
cout << endl;
}
return 0;
}