# Balanced Sequence

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1469    Accepted Submission(s): 155

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

1. (((((((((     全部是左括号

2. ))))))(((((((((     左边全是右括号，右边全是左括号

3. )))))))))))    全部是右括号

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<stack>
#include<cstring>
#include<cmath>
#include<vector>
using namespace std;

char str[100005];

struct node{
int left,right,l_r;	  // l_r 表示 left - right ，即差值
}nod[100005];

stack<char> sta;
vector<node> v1,v2,v3;

bool cmp(node a,node b){
if(a.l_r >= 0 && b.l_r >= 0){	// 左括号都做正贡献的时候，右括号少的放左边
return a.right < b.right;
}else if(a.l_r >= 0){			// 左括号做正贡献的放左边
return 1;
}else if(b.l_r >= 0){
return 0;
}else{
return a.left > b.left;		// 左括号做负贡献的话，左括号多的放左边
}
}

void init(){
v1.clear();
v2.clear();
v3.clear();
}

int main(){
int t,n;
scanf("%d",&t);
while(t--){
scanf("%d",&n);
int ans = 0;
init();
for(int i = 1;i <= n;i++){
scanf("%s",str);
int len = strlen(str);
for(int j = 0;j < len;j++){
if(j == 0){
sta.push(str[j]);
continue;
}
if(str[j] == '('){
sta.push('(');
}else{
if(!sta.empty() && sta.top() == '('){
sta.pop();
ans++;
}else{
sta.push(')');
}
}
}
nod[i].left = 0;
nod[i].right = 0;
while(!sta.empty()){
if(sta.top() == '('){
nod[i].left++;
}else{
nod[i].right++;
}
sta.pop();
}
nod[i].l_r = nod[i].left - nod[i].right;
if(nod[i].left > 0 && nod[i].right == 0){
v1.push_back(nod[i]);
}else if(nod[i].left == 0 && nod[i].right > 0){
v3.push_back(nod[i]);
}else if(nod[i].left > 0 && nod[i].right > 0){
v2.push_back(nod[i]);
}
}
if(v2.size() > 1)
sort(v2.begin(),v2.end(),cmp);
int left = 0;
for(int i = 0;i < v1.size();i++){
left += v1[i].left;
}
for(int i = 0;i < v2.size();i++){
int tmp = min(left,v2[i].right);
ans += tmp;
left = left - tmp + v2[i].left;
}
for(int i = 0;i < v3.size();i++){
int tmp = min(left,v3[i].right);
ans += tmp;
left -= tmp;
if(left == 0)
break;
}
printf("%d\n",ans * 2);
}
return 0;
}