CSES - Shared codeLink to this code:
https://cses.fi/paste/c75b97e42315d3953004ff/
//PPAP_1264589
#include <bits/stdc++.h>
#define Task "A"
#define up(i,a,b) for (int i = a; i <= b; i++)
#define ep emplace_back
using namespace std;
const int maxn = 1e5 + 10;
int dp[maxn];
int existed[maxn];
int tr[maxn];
int deg[maxn];
bool inchain[maxn];
vector<int> a[maxn];
int n,m;
void in(){
cin >> n >> m;
up(i,1,m){
int u,v;
cin >> u >> v;
if (existed[u] == v) continue;
existed[u] = v;
a[u].ep(v);
++deg[v];
}
}
queue<int> Q;
void topo_sort(){
up(i,1,n) if (deg[i] == 0) Q.push(i);
while (!Q.empty()){
int u = Q.front();
Q.pop();
for (int v : a[u]){
if (dp[v] < dp[u] + 1 && inchain[u]){
dp[v] = dp[u] + 1;
tr[v] = u;
inchain[v] = 1;
}
if (--deg[v] == 0) Q.push(v);
}
}
}
void Fpath(){
int x = n;
vector<int> path;
while (x != 1){
path.ep(x);
x = tr[x];
}
path.ep(1);
reverse(path.begin(), path.end());
for (auto x : path) cout << x << " ";
}
signed main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
if (fopen(Task".inp", "r")){
freopen (Task".inp", "r", stdin);
freopen (Task".out", "w", stdout);
}
in();
inchain[1] = 1;
dp[1] = 1;
topo_sort();
if (!inchain[n]){
cout << "IMPOSSIBLE";
return 0;
}
cout << dp[n] << "\n";
Fpath();
}
// Algorithmic logic