Untitled
unknown
plain_text
5 months ago
1.8 kB
4
Indexable
#include <iostream> #include <vector> #include <stack> #include <algorithm> using namespace std; const int INF = -1e9; void topologicalSort(int node, vector<vector<int>>& adj, vector<bool>& visited, stack<int>& topoStack) { visited[node] = true; for (int neighbor : adj[node]) { if (!visited[neighbor]) { topologicalSort(neighbor, adj, visited, topoStack); } } topoStack.push(node); } int main() { int n, m; cin >> n >> m; vector<vector<int>> adj(n + 1); vector<int> dp(n + 1, INF); vector<int> parent(n + 1, -1); for (int i = 0; i < m; i++) { int a, b; cin >> a >> b; adj[a].push_back(b); } stack<int> topoStack; vector<bool> visited(n + 1, false); for (int i = 1; i <= n; i++) { if (!visited[i]) { topologicalSort(i, adj, visited, topoStack); } } dp[1] = 0; while (!topoStack.empty()) { int city = topoStack.top(); topoStack.pop(); if (dp[city] != INF) { for (int nextCity : adj[city]) { if (dp[city] + 1 > dp[nextCity]) { dp[nextCity] = dp[city] + 1; parent[nextCity] = city; } } } } if (dp[n] == INF) { cout << "IMPOSSIBLE" << endl; } else { cout << dp[n] + 1 << endl; vector<int> path; for (int city = n; city != -1; city = parent[city]) { path.push_back(city); } reverse(path.begin(), path.end()); for (int city : path) { cout << city << " "; } cout << endl; } return 0; }
Editor is loading...
Leave a Comment