ParenthesesDiv1Hard
SRM 688 · 2016-04-01 · by cgy4ever
Problem Statement
- The empty string "" is a correct sequence.
- If "X" and "Y" are correct sequences, then "XY" (the concatenation of X and Y) is a correct sequence.
- If "X" is a correct sequence, then "(X)" is a correct sequence.
- Each correct parentheses sequence can be derived using the above rules.
We can define the depth and the cost of a correct parentheses sequence recursively as follows:
- The empty string "" has depth 0 and cost 0.
- Suppose that "S" = "(A)", where A is a correct parentheses sequence. Then we have depth(S) = depth(A)+1 and cost(S) = cost(A) + depth(S)^2.
- Suppose that "S" = "AB", where A and B are correct parentheses sequences. Then we have depth(S) = max(depth(A),depth(B)) and cost(S) = cost(A) + cost(B).
- The depth of "(((())))" is 4, the depth of "()()()" is 1, and the depth of "(())()" is 2.
- The cost of "(((())))" is 4^2 + 3^2 + 2^2 + 1^2 = 30, the cost of "()()()" is 1^2 + 1^2 + 1^2 = 3, and the cost of "(())()" is 6.
You are given a
Your primary goal is to make sure that both s1 and s2 are correct parentheses sequences. If this goal cannot be achieved, return -1.
Your secondary goal is to make cost(s1) + cost(s2) as small as possible. Compute and return the smallest possible value of cost(s1) + cost(s2).
Notes
- Pay attention to the unusual time limit.
Constraints
- s will contain between 1 and 150 elements, inclusive.
- Each character in s will be '(' or ')'.
Statement by TopCoder, Inc. — view the original on the archive.
"(())" Returns: 2
The optimal solution is to split s into s1 = s2 = "()". (For example, s1 will be the characters at indices 0 and 2 and s2 will be the characters at indices 1 and 3.) For this split we have cost(s1) = cost(s2) = 1.
"((())())(()()())" Returns: 11
One optimal solution is: s = ((())())(()()()) s1 = () () ()()() s2 = (( ) )( ) Cost(s1) = 5, Cost(s2) = 6.
"())(()" Returns: -1
This s cannot be split into two correct sequences.
"(((((((((())))))))))" Returns: 110
"()" Returns: 1
Submissions are judged against all 111 archived test cases, of which 5 are shown here. Case numbers match the judge’s.
Language: C++17 · define a public class ParenthesesDiv1Hard with a public method int minCost(string s) · 111 test cases · 2 s / 256 MB per case