化简到最后就三种类型,一种是全是),一直是全是(,一种是))((。
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<string>
#include<vector>
#include<queue>
#include<cmath>
#include<set>
#include<map>
#include<unordered_map>
using namespace std;
#define LL long long
typedef unsigned long long ull;
#define eps (1e-9)
const int maxn = 1e5 + 10;
const int inf = 0x3f3f3f3f;
const int bas = 131;
const LL mod = 999911659;
struct node
{
int L, r, sum;
}a[maxn];
char str[maxn];
bool cmp(node a, node b)
{
if (a.L > a.r && b.L > b.r) return a.r < b.r;
//如果现在两个都是左括号大于右括号,那么右括号多的要放后面,因为现在右括号少的匹配最大数量就是它自己,那么现在
//b的右括号比a的多,而a的左括号又比a的右括号多,所以b在后面贡献会更大。
if (a.L > a.r && b.L <= b.r) return true;
if (a.L <= a.r && b.L > b.r) return false;
if (a.L <= a.r && b.L <= b.r) return a.L > b.L;
}
int main()
{
int t;
scanf("%d", &t);
while (t--)
{
int n;
scanf("%d", &n);
for (int i = 1; i <= n; i++)
{
a[i].L = a[i].r = a[i].sum = 0;
}
for (int i = 1; i <= n; i++)
{
scanf("%s", str + 1);
int len = strlen(str + 1);
for (int j = 1; j <= len; j++)
{
if (str[j] == '(')
{
a[i].L++;
}
else
{
if (a[i].L > 0)
{
a[i].L--;
a[i].sum++;
}
else a[i].r++;
}
}
}
sort(a + 1, a + n + 1, cmp);
int ans = 0, ansl = 0;
for (int i = 1; i <= n; i++)
{
ans += a[i].sum;
int tmp = min(ansl, a[i].r);
ansl -= tmp;
ans += tmp;
ansl += a[i].L;
}
printf("%d\n", ans * 2);
}
return 0;
}