-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlongest_path.cpp
47 lines (42 loc) · 987 Bytes
/
longest_path.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// added
#include <bits/stdc++.h>
using namespace std;
int longest_path(const vector<vector<int>> &adj) {
int n = adj.size();
vector<vector<int>> inv(n);
for (int a = 0; a < n; a++) {
for (auto b : adj[a]) {
inv[b].push_back(a);
}
}
vector<int> len(n, -1);
function<void(int)> set_len = [&](int v) {
if (len[v] != -1) return;
if (inv[v].empty()) {
len[v] = 0;
return;
}
int nax = 0;
for (int u : inv[v]) {
set_len(u);
nax = max(nax, len[u]);
}
len[v] = nax + 1;
};
for (int i = 0; i < n; i++) {
set_len(i);
}
return *max_element(len.begin(), len.end());
}
int main() {
int n, m;
cin >> n >> m;
vector<vector<int>> adj(n);
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
a--, b--;
adj[a].push_back(b);
}
cout << longest_path(adj) << endl;
}