Best Parenthesis
InterviewTime limit1sMemory limit256 MB
Given a balanced parenthesis string encoded as 0/1 values, compute its recursively defined score modulo 12345678910.
- Level
Medium5 of 10
- Topics
- Stack, Recursion, Implementation, Math
- Solved
- No attempts yet
Problem
Recently the cows have been competing with strings of balanced parentheses, comparing them to see whose string is best.
A balanced parenthesis string is scored by the following rules (every string considered here is balanced):
- The string
()has score . - If a string
Ahas score , then(A)has score . - If strings
AandBhave scores and , then their concatenationABhas score .
For example, .
Bessie wants to beat every other cow, so she must be able to compute the score of a given string. Given a balanced parenthesis string of length (), compute its score.
Input
- Line 1: a single integer .
- Lines 2 to : line contains one integer describing the -th character of the string — if it is
(, or if it is).
Output
- Line 1: the score of the string. Because this value can be very large, output it modulo .
Hint
The input encodes the string one character at a time: each value means an opening parenthesis ( and each value means a closing parenthesis ). Concatenate these characters in order to reconstruct the original string, then apply the scoring rules.