Problem : Link.
My solution
I simply did bfs from node 1 and found the maximum distance from this node to all other nodes
const int INF = 1e9;
const int sz = 1e5+1;
int n,m;
vector<int> last(sz);
vector<vector<int> > adj(sz);
vector<int> d(sz,0);
void solve()
{
cin>>n>>m;
for(int i=0; i<m; ++i)
{
int a,b;
cin>>a>>b;
adj[a].push_back(b);
}
queue<int> q;
q.push(1);
while(!q.empty())
{
int s = q.front();
q.pop();
for(auto u : adj[s])
{
if(d[s]+1>d[u])
{
d[u]=1+d[s];
last[u]=s;
q.push(u);
}
}
}
if(d[n]==0)
{
cout<<"IMPOSSIBLE"<<endl;
return;
}
vector<int> ans;
int k=n;
while(k!=1)
{
ans.push_back(k);
k=last[k];
}
ans.push_back(1);
reverse(ans.begin(), ans.end());
cout<<1+d[n]<<endl;
for(int i=0; i<ans.size(); ++i)
cout<<ans[i]<<" ";
cout<<endl;
}
int main()
{
solve();
}
So the solution is O(n+m) but still, there is TLE in one case. Why?