1 #include <stdio.h>
2 #include <iostream>
3 #include <cstdlib>
4 #include <cmath>
5 #include <string>
6 #include <cstring>
7 #include <algorithm>
8 #include <stack>
9 #include <queue>
10 #include <set>
11 #include <map>
12 #include <vector>
13 using namespace std;
14 typedef long long ll;
15 typedef unsigned long long ull;
16
17 #define Faster ios::sync_with_stdio(false),cin.tie(0)
18 #define Read freopen("in.txt", "r", stdin),freopen("out.txt", "w", stdout)
19 const int INF = 0x3f3f3f3f;
20 const int maxn = 1e5 + 5;
21 const int MOD = 1e9 + 7;
22
23 struct node{
24 int left, right;
25 bool operator < (const node& x) const {
26 if(left <= right && x.right < x.left) return false;
27 else if(left > right && x.right >= x.left) return true;
28 if(left <= right && x.right >= x.left) return left > x.left;
29 else return right < x.right;
30 }
31 }a[maxn];
32
33 int main()
34 {
35 Faster;
36 int t;
37 cin >> t;
38 while(t--){
39 int n;
40 cin >> n;
41 int ans = 0;
42 for(int i = 0;i < n;i++){
43 string s;
44 cin >> s;
45 a[i].left = a[i].right = 0;
46 for(int j = 0;j < s.size();j++){
47 if(s[j] == '('){
48 a[i].left++;
49 }
50 else if(s[j] == ')'){
51 if(a[i].left > 0){
52 a[i].left--;
53 ans += 2;
54 }
55 else{
56 a[i].right++;
57 }
58 }
59 }
60 }
61 sort(a, a+n);
62 int now = 0; //记录有多少左括号没有匹配
63 for(int i = 0;i < n;i++){
64 if(a[i].right > now)
65 a[i].right = now;
66 ans += a[i].right*2;
67 now -= a[i].right;
68 now += a[i].left;
69 }
70 cout << ans << endl;
71 }
72 return 0;
73 }