# Problem Description

Chiaki has n strings s1,s2,…,sn consisting of '(' and ')'. A string of this type is said to be balanced:

+ if it is the empty string
+ if A and B are balanced, AB is balanced,
+ if A is balanced, (A) is balanced.

Chiaki can reorder the strings and then concatenate them get a new string t. Let f(t) be the length of the longest balanced subsequence (not necessary continuous) of t. Chiaki would like to know the maximum value of f(t) for all possible t.

Input

There are multiple test cases. The first line of input contains an integer T, indicating the number of test cases. For each test case:
The first line contains an integer n (1≤n≤105) -- the number of strings.
Each of the next n lines contains a string si (1≤|si|≤105) consisting of (' and )'.
It is guaranteed that the sum of all |si| does not exceeds 5×106.

Output

For each test case, output an integer denoting the answer.

Sample Input

2

1

)()(()(

2

)

)(

Sample Output

4

2

Source

2018 Multi-University Training Contest 1

Recommend

liuyiding   |   We have carefully selected several similar problems for you:  6308 6307 6306 6305 6304

①左括号>右括号

②左括号<=右括号

①：左括号<右括号，按照左括号从小到大排

②：左括号>=右括号，按照左括号从大到小排。

#include<bits/stdc++.h>
using namespace std;
const int maxn=100010;

struct node
{
int l,r;
}a[maxn];
int cmp(node a,node b)
{
if(a.l<=a.r&&b.l>b.r) //)少(多 > )多(少
return true;///不变
if(a.l>a.r&&b.l<=b.r) //)多(少 < )少(多
return false;///让a，b交换
if(a.l<=a.r&&b.l<=b.r)//)少(多   )少(多
return a.l<b.l;   //)少的放前面
if(a.l>=a.r &&b.l>b.r)
return a.r>b.r;       //(多的优先
}

int main()
{
int t;
char H[maxn];
char h[maxn];
int n;
scanf("%d",&t);
while(t--)
{
int ans=0;
scanf("%d",&n);
int top;
for(int i=1;i<=n;i++)
{
top=0;
scanf("%s",H);
int kaka=strlen(H);
for(int j=0;j<kaka;j++)
{
if(H[j]==')' && h[top]=='(' &&top>0)
{
ans++;
--top;
}
else
{
h[++top]=H[j];
}
}
a[i].l=0;
a[i].r=0;
for(int j=1;j<=top;j++)
{
if(h[j]==')')
a[i].l++;
else
a[i].r++;
}
}

sort(a+1,a+n+1,cmp);
int num=0;
for(int i=2;i<=n;i++)
{
num+=a[i-1].r;
if(a[i].l>num)
{
ans+=num;
num=0;
}
else
{
ans+=a[i].l;
num-=a[i].l;
}
}
printf("%d\n",ans*2);

}

}