Skip to content

Commit 03e3c34

Browse files
committed
Add Longest Flight Route.cpp for finding the longest path in a directed graph
1 parent 3246a23 commit 03e3c34

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

Longest Flight Route.cpp

+73
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
// say Alhamdulillah
2+
3+
#include <algorithm>
4+
#include <bits/stdc++.h>
5+
using namespace std;
6+
#define ll long long
7+
#define eb emplace_back
8+
9+
#define forr(i, a, b) for (ll i = a; i < b; i++)
10+
#define fast \
11+
ios_base::sync_with_stdio(0); \
12+
cin.tie(0); \
13+
cout.tie(0);
14+
15+
vector<vector<ll>> adj_list;
16+
vector<ll> vis, topoPath;
17+
18+
void dfs(ll curr) {
19+
vis[curr] = 1;
20+
21+
for (ll neigh : adj_list[curr]) {
22+
if (!vis[neigh]) {
23+
dfs(neigh);
24+
}
25+
}
26+
topoPath.emplace_back(curr);
27+
}
28+
29+
int main() {
30+
fast;
31+
ll n, m, x, y, i;
32+
cin >> n >> m;
33+
34+
vector<ll> par(n + 1), dist(n + 1), ans;
35+
adj_list.resize(n + 1);
36+
vis.resize(n + 1, 0);
37+
38+
for (i = 1; i <= m; i++) {
39+
cin >> x >> y;
40+
adj_list[x].emplace_back(y);
41+
}
42+
43+
dfs(1);
44+
45+
if (vis[n] == 0) {
46+
cout << "IMPOSSIBLE\n";
47+
return 0;
48+
}
49+
50+
reverse(topoPath.begin(),topoPath.end());
51+
52+
for (auto i : topoPath) {
53+
for (auto x : adj_list[i]) {
54+
if (dist[i] + 1 > dist[x]) {
55+
dist[x] = dist[i] + 1;
56+
par[x] = i;
57+
}
58+
}
59+
}
60+
61+
x = n;
62+
while (x != 0) {
63+
ans.eb(x);
64+
x = par[x];
65+
}
66+
67+
reverse(ans.begin(), ans.end());
68+
cout << ans.size() << endl;
69+
70+
for (auto x : ans) {
71+
cout << x << " ";
72+
}
73+
}

0 commit comments

Comments
 (0)