题意:
给出n个括号序列,求任意顺序拼接后的序列的最大括号匹配数。
思路:
先在每个串内匹配并消去括号,剩下的可以表示成pair<int,int>=(num(')'),num('('))的一个pair,然后在按照流水线调度的johnson法则排序剩余括号序列的pair并匹配,总体思想是使得浪费的括号数最小。
代码:
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <cstring>
#include <cctype>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <ctime>
#include <map>
#include <list>
#include <set>
#include <stack>
#include <queue>
#include <string>
#include <sstream>
#define pb push_back
#define X first
#define Y second
#define ALL(x) x.begin(),x.end()
#define INS(x) inserter(x,x.begin())
#define pii pair<int,int>
#define qclear(a) while(!a.empty())a.pop();
#define lowbit(x) (x&-x)
#define sd(n) scanf("%d",&n)
#define sdd(n,m) scanf("%d%d",&n,&m)
#define sddd(n,m,k) scanf("%d%d%d",&n,&m,&k)
#define mst(a,b) memset(a,b,sizeof(a))
#define cout3(x,y,z) cout<<x<<" "<<y<<" "<<z<<endl
#define cout2(x,y) cout<<x<<" "<<y<<endl
#define cout1(x) cout<<x<<endl
#define IOS std::ios::sync_with_stdio(false)
#define SRAND srand((unsigned int)(time(0)))
typedef long long ll;
typedef unsigned long long ull;
typedef unsigned int uint;
using namespace std;
const double PI=acos(-1.0);
const int INF=0x3f3f3f3f;
const ll mod=1e9+7;
const double eps=1e-8;
const int maxn=100005;
const int maxm=10005;
struct node {
int l,r;
bool operator < (const node b)const {
if(r<l&&b.r>=b.l)return 1;
if(r>=l&&b.r<b.l)return 0;
if(r<l&&b.r<b.l)return r<b.r;
if(r>=l&&b.r>=b.l)return l>b.l;
}
};
int n;
char str[maxn];
char str1[5000005];
node p[maxn];
void solve() {
int t;
sd(t);
while(t--) {
sd(n);
int ans=0;
for(int i=0; i<n; i++) {
scanf("%s",str);
int len=strlen(str);
int l=0,r=0;
int res=0;
for(int j=0; j<len; j++) {
if(str[j]=='(') {
l++;
} else if(l>0) {
l--;
res++;
} else {
r++;
}
}
ans+=res;
p[i].l=l;
p[i].r=r;
}
sort(p,p+n);
int cur=0;
for(int i=0; i<n; i++) {
int nowl,nowr;
nowl=p[i].l;
nowr=p[i].r;
while(nowr--) {
str1[cur++]=')';
}
while(nowl--) {
str1[cur++]='(';
}
}
int l=0,r=0;
int res=0;
for(int j=0; j<cur; j++) {
if(str1[j]=='(') {
l++;
} else if(l>0) {
l--;
res++;
} else {
r++;
}
}
ans+=res;
ans*=2;
printf("%d\n",ans);
}
return ;
}
int main() {
#ifdef LOCAL
freopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);
#else
// freopen("","r",stdin);
// freopen("","w",stdout);
#endif
solve();
return 0;
}