Sherlock and Parentheses (Large)
InterviewTime limit5sMemory limit512 MB
Given L opening and R closing parentheses, arrange a string of length L+R that maximizes the number of non-empty balanced substrings; output that maximum.
- Level
Medium6 of 10
- Topics
- String, Greedy, Math, Combinatorics
- Solved
- No attempts yet
Problem
Sherlock and Watson learned about balanced parenthesis strings in a programming class. A string made only of the characters ( and ) is balanced when one of the following holds.
- is the empty string.
- has the form
(), where is a balanced string. - has the form , where and are both balanced strings.
Sherlock solved the exercise at once and bragged about it, so Watson gave him another problem. Build a string of length that contains exactly opening parentheses ( and exactly closing parentheses ), and make the number of non-empty balanced substrings as large as possible. Two substrings count as different when they start at different indexes or end at different indexes, even if their contents are the same. itself does not have to be balanced.
Sherlock says that once he knows the maximum, he can build the string himself. Given and , find the maximum possible number of non-empty balanced substrings.
Input
The first line contains the number of test cases . Each of the next lines contains two integers and separated by a space.
Output
For each test case, print one line in the form Case #x: y, where x is the test case number starting from 1 and y is the maximum you found.
Constraints
Notes
For and , the only possible string is (, and it has no non-empty balanced substring.
For and , the string () is optimal, and the whole string is the single balanced substring.
For and , both ()()( and (()() reach the maximum of 3. In ()()(, for example, the balanced substrings are () from index 1 to 2, () from index 3 to 4, and ()() from index 1 to 4.