Skip to content

Commit f7b42fc

Browse files
authored
Update longest-path-with-different-adjacent-characters.cpp
1 parent 0f72ecc commit f7b42fc

File tree

1 file changed

+56
-3
lines changed

1 file changed

+56
-3
lines changed

C++/longest-path-with-different-adjacent-characters.cpp

Lines changed: 56 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,61 @@
11
// Time: O(n)
2-
// Space: O(h)
2+
// Space: O(w)
33

4-
// tree, dfs
4+
// tree, bfs, topological sort
55
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 {
659
public:
760
int longestPath(vector<int>& parent, string s) {
861
vector<vector<int>> adj(size(s));
@@ -54,7 +107,7 @@ class Solution {
54107
// Time: O(n)
55108
// Space: O(h)
56109
// tree, dfs
57-
class Solution2 {
110+
class Solution3 {
58111
public:
59112
int longestPath(vector<int>& parent, string s) {
60113
vector<vector<int>> adj(size(s));

0 commit comments

Comments
 (0)