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.
Example 1:
Input: parent = [-1,0,0,1,1,2], s = “abacbe”
Output: 3
Explanation: The longest path where each two adjacent nodes have different characters in the tree is the path: 0 -> 1 -> 3. The length of this path is 3, so 3 is returned.
It can be proven that there is no longer path that satisfies the conditions.
Example 2:
Input: parent = [-1,0,0,0], s = “aabc”
Output: 3
Explanation: The longest path where each two adjacent nodes have different characters is the path: 2 -> 0 -> 3. The length of this path is 3, so 3 is returned.
Constraints:
- n == parent.length == s.length
- 1 <= n <= 105
- 0 <= parent[i] <= n - 1 for all i >= 1
- parent[0] == -1
- parent represents a valid tree.
- s consists of only lowercase English letters.
题不难, 但是思路很难表达出来, 整体来说就是对于任何一个节点 node, 我们通过经过该节点的两个最长的连续路径的来更新最终结果, 同时返回最长的连续路径来供父节点来计算新的值。
use std::collections::BinaryHeap;
impl Solution {
fn rc(children: &Vec<Vec<usize>>, chars: &Vec<char>, i: usize, ans: &mut i32) -> i32 {
if i == 100000 {
return 0;
}
let sc = chars[i];
let mut equals = BinaryHeap::new();
let mut not_equals = BinaryHeap::new();
for &c in &children[i] {
let length = Solution::rc(children, chars, c, ans);
if c != 100000 {
if chars[c] != sc {
not_equals.push(length);
continue;
}
equals.push(length);
}
}
let neq_first = if let Some(len) = not_equals.pop() {
len
} else {
0
};
let neq_second = if let Some(len) = not_equals.pop() {
len
} else {
0
};
*ans = (*ans).max(neq_first + neq_second + 1);
if let Some(len) = equals.pop() {
*ans = (*ans).max(len);
}
neq_first + 1
}
pub fn longest_path(parent: Vec<i32>, s: String) -> i32 {
let chars: Vec<char> = s.chars().collect();
let mut children = vec![Vec::new(); parent.len()];
for (i, p) in parent.into_iter().enumerate() {
if p != -1 {
children[p as usize].push(i);
}
}
let mut ans = 0;
Solution::rc(&children, &chars, 0, &mut ans);
ans
}
}

给定一棵以0为根的无环树,目标是找到一条最长的路径,使得路径上的相邻节点字符不同。返回这条路径的长度。例如,在一个树中,最长的满足条件的路径是0 -> 1 -> 3,长度为3。问题的关键在于通过每个节点的两个最长连续子路径来更新结果。
1281

被折叠的 条评论
为什么被折叠?



