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
#include<bits/stdc++.h>
#define lowbit(x) (x&(-x))
#define ls(x) (x<<1)
#define rs(x) (x<<1|1)
#define rep(i,a,b) for(int i=a;i<b;i++)
#define per(i,a,b) for(int i=b-a;i>=a;i--)
#define SZ(x) ((int)(x).size())
using namespace std;
typedef long long ll;
typedef vector<int> VI;
typedef pair<int,int> PII;
const int mod=1e9+7;
const int maxn=1e5+10;
struct node{
int l,r;
int id;
}p[maxn];
char str[maxn],stk[maxn];
inline void solve(int& ans,int id){
int top=-1;
int len=strlen(str);
rep(i,0,len){
if(top>-1&&str[i]==')'&&stk[top]=='('){
ans++;top--;
}
else{
stk[++top]=str[i];
}
}
p[id].l=0,p[id].r=0;
rep(i,0,top+1){
if(stk[i]==')')p[id].l++;
else p[id].r++;
}
p[id].id=id;
}
bool cmp(const node& A,const node& B){
//另一种写法
if(min(A.r,B.l)==min(A.l,B.r)) return A.r>B.r;
return min(A.r,B.l)>min(A.l,B.r);
/*
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;
return A.r>B.r;
*/
}
int main(){
// freopen("1002.txt","r",stdin);
// freopen("123.txt","w",stdout);
int T;
scanf("%d",&T);
for(int kase=1;kase<=T;kase++){
int n;
scanf("%d",&n);
int ans=0;
rep(i,1,n+1){
scanf(" %s",str);
solve(ans,i);
}
sort(p+1,p+n+1,cmp);
int num=0;
rep(i,2,n+1){
num+=p[i-1].r;
if(p[i].l>=num){
ans+=num;
num=0;
}
else{
ans+=p[i].l;
num-=p[i].l;
}
}
printf("%d\n",ans*2);
}
return 0;
}
sort排序,用于流水线调度