|
1 | 1 | // Time: O(n)
|
2 |
| -// Space: O(h) |
| 2 | +// Space: O(w) |
3 | 3 |
|
4 |
| -// tree, dfs |
| 4 | +// tree, bfs, topological sort |
5 | 5 | class Solution {
|
| 6 | +public: |
| 7 | + int longestPath(vector<int>& parent, string s) { |
| 8 | + vector<vector<int>> adj(size(s)); |
| 9 | + vector<int> in_degree(size(s)); |
| 10 | + for (int i = 1; i < size(parent); ++i) { |
| 11 | + adj[i].emplace_back(parent[i]); |
| 12 | + ++in_degree[parent[i]]; |
| 13 | + } |
| 14 | + |
| 15 | + const auto& topological_sort = [&s, &adj](vector<int> *in_degree) { |
| 16 | + int result = 1; |
| 17 | + unordered_map<int, vector<int>> top2; |
| 18 | + |
| 19 | + vector<pair<int, int>> q; |
| 20 | + for (int i = 0; i < size(*in_degree); ++i) { |
| 21 | + if (!(*in_degree)[i]) { |
| 22 | + q.emplace_back(i, 1); |
| 23 | + } |
| 24 | + } |
| 25 | + while (!empty(q)) { |
| 26 | + vector<pair<int, int>> new_q; |
| 27 | + for (const auto& [u, l] : q) { |
| 28 | + for (const auto& v : adj[u]) { |
| 29 | + if (!top2.count(v)) { |
| 30 | + top2[v] = vector<int>(2); |
| 31 | + } |
| 32 | + if (s[v] != s[u]) { |
| 33 | + if (l > top2[v][0]) { |
| 34 | + top2[v][1] = top2[v][0]; |
| 35 | + top2[v][0] = l; |
| 36 | + } else if (l > top2[v][1]) { |
| 37 | + top2[v][1] = l; |
| 38 | + } |
| 39 | + } |
| 40 | + if (!--(*in_degree)[v]) { |
| 41 | + new_q.emplace_back(v, top2[v][0] + 1); |
| 42 | + result = max(result, top2[v][0] + top2[v][1] + 1); |
| 43 | + top2.erase(v); |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + q = move(new_q); |
| 48 | + } |
| 49 | + return result; |
| 50 | + }; |
| 51 | + return topological_sort(&in_degree); |
| 52 | + } |
| 53 | +}; |
| 54 | + |
| 55 | +// Time: O(n) |
| 56 | +// Space: O(h) |
| 57 | +// tree, dfs |
| 58 | +class Solution2 { |
6 | 59 | public:
|
7 | 60 | int longestPath(vector<int>& parent, string s) {
|
8 | 61 | vector<vector<int>> adj(size(s));
|
@@ -54,7 +107,7 @@ class Solution {
|
54 | 107 | // Time: O(n)
|
55 | 108 | // Space: O(h)
|
56 | 109 | // tree, dfs
|
57 |
| -class Solution2 { |
| 110 | +class Solution3 { |
58 | 111 | public:
|
59 | 112 | int longestPath(vector<int>& parent, string s) {
|
60 | 113 | vector<vector<int>> adj(size(s));
|
|
0 commit comments