You are given a bracket sequence ss of length nn, where nn is even (divisible by two). The string ss consists of n2n2 opening brackets '(' and n2n2 closing brackets ')'.
In one move, you can choose exactly one bracket and move it to the beginning of the string or to the end of the string (i.e. you choose some index ii, remove the ii-th character of ss and insert it before or after all remaining characters of ss).
Your task is to find the minimum number of moves required to obtain regular bracket sequence from ss. It can be proved that the answer always exists under the given constraints.
Recall what the regular bracket sequence is:
- "()" is regular bracket sequence;
- if ss is regular bracket sequence then "(" + ss + ")" is regular bracket sequence;
- if ss and tt are regular bracket sequences then ss + tt is regular bracket sequence.
For example, "()()", "(())()", "(())" and "()" are regular bracket sequences, but ")(", "()(" and ")))" are not.
You have to answer tt independent test cases.
Input
The first line of the input contains one integer tt (1≤t≤20001≤t≤2000) — the number of test cases. Then tt test cases follow.
The first line of the test case contains one integer nn (2≤n≤502≤n≤50) — the length of ss. It is guaranteed that nn is even. The second line of the test case containg the string ss consisting of n2n2 opening and n2n2 closing brackets.
Output
For each test case, print the answer — the minimum number of moves required to obtain regular bracket sequence from ss. It can be proved that the answer always exists under the given constraints.
Example
Input
4 2 )( 4 ()() 8 ())()()( 10 )))((((())
Output
1 0 1 3
Note
In the first test case of the example, it is sufficient to move the first bracket to the end of the string.
In the third test case of the example, it is sufficient to move the last bracket to the beginning of the string.
In the fourth test case of the example, we can choose last three openning brackets, move them to the beginning of the string and obtain "((()))(())".
题意: 给出一段偶数长度括号序列,其中一半是左括号,一半是右括号,求最少移动多少次可以使整个序列匹配。
分析: 如果一段括号序列已经匹配,之后操作肯定不会破坏它们的匹配,因此可以直接忽视它们。设有a组括号未匹配,由题目得一定有a/2个左括号和a/2个右括号需要匹配,另外可以发现删去匹配括号后剩下不匹配的括号序列一定是类似)))(((这样的,因此要想移动次数最少,可以直接把右括号移到左括号右边,最后需要移动a/2次。题目转化为求序列中有几个括号不匹配,用栈模拟一下就行。
具体代码如下:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
#include <cstring>
using namespace std;
signed main()
{
int T;
cin >> T;
char s[100];
int st[100];
while(T--)
{
int n;
cin >> n;
scanf("%s", s+1);
int top = 0;
for(int i = 1; i <= n; i++)
if(s[i] == '(')
st[++top] = 1;
else
{
if(st[top] == 1)
top--;
else
st[++top] = 2;
}
printf("%d\n", top/2);
}
return 0;
}