题目:n个包含 ’(‘ 和 ’)’ 的字符串,将这些字符串任意排序,求能过匹配消除多少括号。
贪心排个序,WA了十几发,看题解才知道,唉好菜啊啊啊。。还有因为没初始化???
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+10;
struct node{
int l,r;
}a[maxn];
char s[maxn],st[maxn];
bool cmp(const node &a,const node&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.r>=a.l&&b.r>=b.l)//)少(多 )少(多
return a.l<b.l; //)少的放前面
return a.r>b.r; //(多的优先
}
int t,n;
int main()
{
//freopen("in.txt","r",stdin);
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
int ans=0;
for(int i=1;i<=n;i++)
{
scanf("%s",s);
int len=strlen(s),top=0;
for(int j=0;j<len;j++)
{
if(s[j]==')'&&top>0&&st[top]=='(')
{
ans++;
top--;
}
else st[++top]=s[j];
}
a[i].l=a[i].r=0;
for(int j=1;j<=top;j++)
if(st[j]=='(')
a[i].l++;
else a[i].r++;
}
sort(a+1,a+n+1,cmp);
int num=0;
for(int i=2;i<=n;i++)
{
num+=a[i-1].r;
if(a[i].l>num)
{
ans+=num;
num=0;
}
else
{
ans+=a[i].l;
num-=a[i].l;
}
}
printf("%d\n",ans*2);
}
return 0;
}