#P16571. [ICPC 2026 APC] Deformed Balance

[ICPC 2026 APC] Deformed Balance

题目描述

In this problem, a concatenation of two strings T T and U U is denoted by T+U T+U .

A string consisting only of parentheses (opening parentheses '(' or closing parentheses ')') is balanced if and only if it is one of the following.

  • An empty string.
  • The concatenation of two non-empty balanced strings.
  • The concatenation (+T+) \texttt{(} + T + \texttt{)} , where T T is a balanced string.

For example, "()" and "(())()" are balanced, while "()(" and "((()" are not.A string is deformed if and only if it is one of the following.

  • The string ")".
  • The concatenation T+)+U T + \texttt{)} + U , where T T and U U are deformed strings.
  • The concatenation (+T+( \texttt{(} + T + \texttt{(} , where T T is a deformed string.

For example, "()(" and "))()(" are deformed, while "()" and "(()" are not.A string T T has a deformed balance if T T is deformed and the concatenation T+) T + \texttt{)} is balanced. For example, the string "()(" has a deformed balance.

You are given a string S S of length n n consisting only of parentheses. Under the given input constraints, it can be shown that there exist strings X X and Y Y such that the concatenation X+S+Y X + S + Y has a deformed balance. Determine the minimum possible value of X+Y |X| + |Y| (the sum of the lengths of X X and Y Y ).

输入格式

The first line of input contains one integer t t ( 1t10000 1 \le t \le 10\,000 ) representing the number of test cases. After that, t t test cases follow. Each of them is presented as follows.

The first line of each test case contains an integer n n ( 1n106 1 \le n \le 10^6 ).

The second line contains a string S S of length n n , consisting only of '(' or ')'.

The sum of n n across all test cases in one input file does not exceed 106 10^6 .

输出格式

For each test case, output the minimum possible value of X+Y |X|+|Y| such that the concatenation X+S+Y X + S + Y has a deformed balance.

3
3
()(
1
)
7
(())())
0
2
4

提示

Explanation for the sample input/output #1

For the first test case, the given string already has a deformed balance.

For the second test case, setting both X X and Y Y to "(" yields the concatenation "()(", which has a deformed balance. The value of X+Y |X|+|Y| is 2 2 .

For the third test case, it suffices to set X X to "((()" and Y Y to an empty string to attain the minimum value of X+Y |X|+|Y| .