Balanced Tree Path
Time limit2sMemory limit2048 MB
Count the paths in a tree whose node labels, read in path order, form a balanced bracket string.
Problem
Each node of a tree is labeled with one of the characters ()[]{}. A path is a sequence of one or more nodes in which no node repeats and every pair of adjacent nodes is joined by an edge. A path is balanced if the characters of its nodes, concatenated in order, form a balanced string.
A string is balanced by these rules:
- The empty string is balanced.
- If is balanced, then , , and are balanced.
- If and are balanced, then the concatenation is balanced.
Count the balanced paths in the whole tree.
Input
The first line contains an integer ().
The second line contains a string of characters, each one of ()[]{}.
Each of the next lines contains two integers and (), meaning that nodes and are connected by an edge. The graph is a tree.
Output
Print a single integer: the number of balanced paths.