Longest Path With Different Adjacent Characters

Really rolls of the tongue, doesn't it? An editorial is in the works, but here's the code:


_49
class Solution {
_49
public:
_49
int longestPath(vector<int>& parent, string s) {
_49
const int n = parent.size();
_49
_49
vector<int> childOf (n, -1),
_49
siblingOf (n, -1),
_49
lengthFrom (n, -1);
_49
_49
// keep a flat, singly linked connection through the graph
_49
for (int i = 1; i < n; ++i) {
_49
if (s[i] != s[parent[i]]) {
_49
siblingOf[i] = childOf[parent[i]];
_49
childOf[parent[i]] = i;
_49
}
_49
}
_49
_49
int longest = 0;
_49
_49
const function<int(int)> traverse = [&] (int node) {
_49
// if the best length from this node is known, return it immediately
_49
if (lengthFrom[node] != -1) return lengthFrom[node];
_49
_49
// we either treat this node as the root and take the two best of its branches,
_49
// or pass the best branch from this node up to its parent
_49
int rank_1 = 0, rank_2 = 0;
_49
_49
for (int child = childOf[node]; child != -1; child = siblingOf[child]) {
_49
int val = traverse(child);
_49
_49
if (val > rank_1) {
_49
rank_2 = rank_1;
_49
rank_1 = val;
_49
} else if (val > rank_2) {
_49
rank_2 = val;
_49
}
_49
}
_49
_49
longest = max(longest, 1 + rank_1 + rank_2);
_49
lengthFrom[node] = rank_1 + 1;
_49
return lengthFrom[node];
_49
};
_49
_49
for (int i = 0; i < n; ++i)
_49
traverse(i);
_49
_49
return longest;
_49
}
_49
};

If you found this solution helpful, consider leaving a star!