C. Move Brackets
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
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
Copy
4 2 )( 4 ()() 8 ())()()( 10 )))((((())
output
Copy
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 "((()))(())".
#include<iostream>
using namespace std;
int t,n;
char a[55];
int main()
{
cin>>t;
while(t--)
{
cin>>n;
int sum=0,count=0;
for(int i=1;i<=n;i++)
{
cin>>a[i];
if(a[i]==')')
{
sum-=1;
}
else sum+=1;
if(sum<0)
{
count++;
sum=0;//一定要为零,因为下一个是与下下个看是否配对
}
}
cout<<count<<endl;
}
}