Balanced Paths
Time limit3sMemory limit256 MB
Count ordered node pairs whose labels along the tree path form a balanced parenthesis string.
- Level
Hard8 of 10
- Topics
- Divide and conquer, Hash map, Prefix sum, Tree
- Solved
- No attempts yet
Problem
You are given an undirected tree with nodes, numbered through . Every node is labeled with either ( or ). For two nodes and , let be the string obtained by concatenating the labels of the nodes on the simple path from to , read in order from to . On a tree the simple path between two nodes is unique.
A balanced string is defined as follows.
- The empty string is balanced.
- If is balanced, then the concatenation of
(, ,)is balanced. - If and are balanced, then their concatenation is balanced.
- No other string is balanced.
Count the ordered pairs of nodes such that is balanced.
Input
The first line contains an integer (), the number of nodes of the tree.
The second line contains a string of length . Each character of the string is ( or ), and the -th character is the label of node .
Each of the next lines contains two integers and (), meaning that node and node are joined by an edge. The given graph is a tree.
Output
Print one line containing the number of ordered pairs such that is balanced.