CSES - Shared codeLink to this code:
https://cses.fi/paste/0f33adb06516d81c29b492/
#include <bits/stdc++.h>
using namespace std;
//#pragma GCC optimize("Ofast","unroll-loops","omit-frame-poller","inline","03")
#define all(x) (x).begin(), (x).end()
typedef long double ld;
typedef long long ll;
typedef pair <int, int> ii;
typedef __int128 LL;
vector <int> dp, sol;
vector <vector <int>> ady;
int solve(int x) {
int &aux = dp[x];
if(aux != -1)return aux;
aux = 0;
for(int to : ady[x])
aux = max(aux, solve(to));
if(aux)aux++;
return aux;
}
int n, m;
void dfs(int x) {
cout << x;
if(x == n) {
cout << '\n';
return;
}
cout << ' ';
for(int to : ady[x])
if(dp[x] == dp[to] + 1) {
dfs(to);
return;
}
}
int x, y;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m;
dp.resize(n + 1, -1);
ady.resize(n + 1, vector <int> ());
while(m--) {
cin >> x >> y;
ady[x].push_back(y);
}
dp[n] = 1;
int sol = solve(1);
if(!sol) {
cout << "IMPOSSIBLE\n";
return 0;
}
cout << sol << '\n';
dfs(1);
return 0;
}