Parentheses Tree
Time limit1sMemory limit1024 MB
Given a balanced parentheses string that encodes a rooted ordered tree, sum the distances from the root to every leaf.
- Level
Easy3 of 10
- Topics
- String, Tree, Implementation
- Solved
- No attempts yet
Statement
A rooted ordered tree can be written as a string of matched parentheses . A tree with a single node is written as (). When the root of has ordered subtrees attached as its children, is defined as follows:
( )
Here means concatenation of two strings. The figure below shows two rooted ordered trees. The string representations and are ((()()())()) and (()((()(()))())), respectively.

The distance from the root to a leaf is the number of edges on the path from the root to that leaf. In the figure, the root nodes are blue, and the distance from the root to each leaf is shown. The sums of the root-to-leaf distances are for and for .
Given a string of matched parentheses that represents exactly one rooted ordered tree, output the sum of the distances from the root to all leaf nodes.
Input
The input is one line containing a string of matched parentheses that represents one rooted ordered tree. The string contains no characters other than parentheses. Its length is at least and at most .
Output
Print one line containing the sum of the distances from the root of the tree to all leaf nodes.