[LeetCode] Longest Path With Different Adjacent Characters

2246. Longest Path With Different Adjacent Characters

You are given a tree (i.e. a connected, undirected graph that has no cycles) rooted at node 0 consisting of n nodes numbered from 0 to n - 1. The tree is represented by a 0-indexed array parent of size n, where parent[i] is the parent of node i. Since node 0 is the root, parent[0] == -1.

You are also given a string s of length n, where s[i] is the character assigned to node i.

Return the length of the longest path in the tree such that no pair of adjacent nodes on the path have the same character assigned to them.

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
class Solution {
int res = 0;
vector<vector<int>> g;

int helper(int u, string& s) {
priority_queue<int, vector<int>, greater<int>> pq;
for(auto& v : g[u]) {
int path = helper(v,s);
if(s[v] != s[u]) {
pq.push(path);
if(pq.size() > 2) pq.pop();
}
}

while(pq.size() < 2) pq.push(0);

int path1 = pq.top(); pq.pop();
int path2 = pq.top(); pq.pop();

res = max(res, path1 + path2 + 1);

return path2 + 1;
}
public:
int longestPath(vector<int>& p, string s) {
int n = p.size(), root = -1;
g = vector<vector<int>>(n);

for(int i = 0; i < n; i++) {
if(p[i] == -1) root = i;
else g[p[i]].push_back(i);
}

return max(helper(root, s), res);
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/17/PS/LeetCode/longest-path-with-different-adjacent-characters/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.