Balanced Trees
Time limit1sMemory limit128 MB
Given a tree whose nodes are labeled with parentheses, find the maximum nesting depth over all paths that spell a balanced parenthesis string.
- Level
Hard8 of 10
- Topics
- Tree, DFS, Divide and conquer, Dynamic programming
- Solved
- No attempts yet
Problem
Farmer John's farm has the shape of a giant tree of pastures (). Every pasture is labeled with either ( or ). Because the farm is a tree, there is exactly one simple path between any pair of pastures.
Reading the labels along a path, in a chosen direction, spells a string of parentheses. Some of these strings are balanced. Among all balanced strings that can be read off paths of the tree, Farmer John wants the largest possible nesting depth.
The nesting depth of a balanced parenthesis string is the maximum, over all of its prefixes, of the number of ( minus the number of ) in that prefix. For example, ()()() has nesting depth , while ((()))() has nesting depth . Writing the running excess of ( under each character makes this clear:
((()))()
12321010
Here is an example farm, each pasture drawn with its label:
'('--'('--')'--'('--')'
| |
')' ')'--'('--'('
| |
')' '('--')'--')'--')'--'('
Because a path is read in one direction, the same two pastures traversed the other way spell the reversed string (for instance () versus )(); both directions are allowed.
For the farm above, the deepest balanced string is ((())), with nesting depth , obtained by walking from A to B:
'('--'('--')'--'('--')'
| |
')' ')'--'('--'(' < A
| |
')' '('--')'--')'--')'--'('
^C ^B
Note that this is different from the longest balanced string; for example (())(()), from A to C, has length but a smaller nesting depth.
Output the nesting depth of the deepest balanced path in the tree. If no path spells a balanced string, output .
Input
- Line : a single integer , the number of nodes in the tree.
- Lines : line contains a single integer with , denoting an edge between node and node .
- Lines : line contains either
(or), the label of node .
Output
- A single integer: the maximum nesting depth among all balanced paths of the tree, or if no balanced path exists.
Hint
This is the farm from the problem statement, with node numbers shown below:
1'('--4'('--6')'--7'('--8')'
| |
2')' 5')'--9'('--10'('
| |
3')' 11'('--12')'--13')'--14')'--15'('
The deepest balanced path is , which spells ((())) and has nesting depth .