CSES - Shared codeLink to this code:
https://cses.fi/paste/95851f6ac3e4e45919f087/
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <string>
#include <algorithm>
#include <string>
#include <cmath>
#include <numeric>
#include <unordered_set>
using namespace std;
//Macros
#define ll long long int
#define endl "\n"
#define fastIO ios_base::sync_with_stdio(false);cin.tie(NULL);
#define pb push_back
#define pll pair<ll,ll>
#define F first
#define S second
#define ml map<ll,ll>
#define vl vector<ll>
#define vs <vector <string>>
#define vvl vector <vector<ll>>
#define vpl vector <pair<ll,ll>>
#define vlvlpl vector <vector<pair<ll,ll>>>
#define pl pair<ll,ll>
#define isTestCases 0
#define showTime 0
const ll nodes = 2e5 + 10;
vl adj[nodes];
vector <ll> parent(nodes,-1);
vector <ll> inNodes(nodes);
vector <ll> dep(nodes);
ll n,m;
void addEdges(ll &m ){
for(ll i = 0;i<m;i++) {
ll x,y;
cin>>x>>y;
adj[x].push_back(y);
inNodes[y]++;
}
}
struct cmp
{
bool operator() (const pl &a, const pl &b)const{
return (a.S>b.S);
}
};
void traverse(){
ll curnd = n;
vector <ll> ans;
while(parent[curnd]!=-1){
ans.push_back(curnd);
curnd = parent[curnd];
}
ans.push_back(1);
cout<<ans.size()<<endl;
for(ll i = ans.size()-1;i>=0;i--)cout<<ans[i]<<' ';
}
void topsort(queue <ll> &que){
while (!que.empty()) {
ll node = que.front();
que.pop();
// Enqueue all adjacent of f and mark them visited
for(ll x:adj[node]){
inNodes[x]--;
if(inNodes[x] == 0){
parent[x] = node;
que.push(x);
}
}
}
}
void solve(){
cin>>n>>m;
vl cst (n+1);
for(ll i=2;i<=n;i++){
cst[i] = INT64_MAX;
}
cst[0]=0;
addEdges(m);
queue <ll> que;
vector <ll> ans;
for(ll i =2;i<=n;i++){
if(inNodes[i]==0 )que.push(i);
}
topsort(que);
que.push(1);
parent[n]=-1;
topsort(que);
if(parent[n] ==-1)
cout<<"IMPOSSIBLE"<<endl;
else traverse();
}
int main(){
fastIO
ll t=1;
#if isTestCases
cin>>t;
#endif
while(t--){
solve();
}
return 0;
}