#P9356. 「SiR-1」Bracket
「SiR-1」Bracket
Background
Everything that kills me makes me feel alive.
Problem Description
Mirika has a bracket sequence of length .
For a bracket sequence , Mirika can perform two operations:
- Rotation: choose a position satisfying , and change into $S_iS_{i+1}\cdots S_{\lvert S\rvert}S_1S_2\cdots S_{i-2}S_{i-1}$.
- Insertion: insert one bracket (either a left bracket or a right bracket) at any position in the sequence.
Mirika defines the weight of a bracket sequence as the minimum number of operations needed to turn this bracket sequence into a valid bracket sequence.
The definition of a valid bracket sequence is:
- The empty string is a valid bracket sequence.
- If is a valid bracket sequence, then is also a valid bracket sequence.
- If both and are valid bracket sequences, then is also a valid bracket sequence.
Now Mirika wants to compute:
where denotes the contiguous subsequence formed by .
However, Mirika is too weak to compute it, so she has to ask you for help.
Input Format
There are multiple test cases in each test point.
The first line contains a positive integer , denoting the number of test cases.
For each test case, the first line contains a positive integer .
The second line contains a bracket sequence of length .
Output Format
Output a total of lines. The -th line contains one integer, denoting the answer for the -th test case.
5
2
((
4
())(
5
()(()
5
()()(
15
()())(())))()()
4
11
16
12
241
Hint
Sample Explanation
For :
- Consider . Perform a rotation operation with , then . Since is a valid bracket sequence, . It can be proven that there is no better strategy.
- Consider . Perform a rotation operation with , then insert a left bracket at the beginning of the sequence, then $\texttt{))(} \Rightarrow \texttt{)()} \Rightarrow \texttt{()()}$. Since is a valid bracket sequence, . It can be proven that there is no better strategy.
Constraints and Notes
This problem uses bundled test.
- Subtask 0 (15 pts): , .
- Subtask 1 (20 pts): , .
- Subtask 2 (5 pts): contains no right brackets.
- Subtask 3 (10 pts): for all integers , .
- Subtask 4 (30 pts): , .
- Subtask 5 (20 pts): no special constraints.
For all testdata, , , .
Translated by ChatGPT 5