MicrosoftOA #1
Longest Path with Alternating Letters in Tree
Estimated HardJudge-ready
Topics (AI-labelled)Tree PathsDP Basics
Each node of a tree is labeled a or b. Find the maximum number of nodes on a simple path in which adjacent nodes have different letters. The path does not have to pass through the root.
Input
This site's input: the first line contains N (1..100000), the second line contains N characters a/b, and the third line contains N parent indices (0-based); the root's parent is −1. The input is guaranteed to form exactly one tree, and the root may have any index.
Output
Output a single integer, the answer.
Example 1
Input:
2
ab
-1 0
Output:
2
Example 2
Input:
5
abbab
-1 0 0 0 2
Output:
3
Example 3
Input:
1
a
-1
Output:
1
Example notes
Example 1: the two nodes have different letters, so both can be visited; the answer is 2.
Example 2: the path 1—0—2 has letters b, a, b and length 3; there is no longer valid path.
Example 3: there is only the root, so the longest path contains 1 node.
Editorial
Loading solution…