http://acm.hdu.edu.cn/showproblem.php?pid=6299
| Problem Description Chiaki has n strings s1,s2,…,sn consisting of '(' and ')'. A string of this type is said to be balanced:
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:
Output For each test case, output an integer denoting the answer.
Sample Input 2 1 )()(()( 2 ) )(
Sample Output 4 2 |
题意:
进行括号匹配,将N个段随意组合,然后进行括号匹配。问最多可以匹配多少括号
分析:
先用栈进行预处理,将n个段最后化简为a个 " ) " 和b个“(”,然后用优先队列优先处理min(a,b)的较大的两组实现贪心,然后将新产生的加入队列。。。
代码:
#include<bits/stdc++.h>
using namespace std;
char s[100005];
struct node
{
int st,et;
bool operator<(const node &aa)const
{
return min(st,et)<min(aa.st,aa.et);
}
};
priority_queue<node>q;
stack<char>c;
int main()
{
int t,i,j,len,sum,aa,bb,tt,n;
node now,noww;
scanf("%d",&t);
while(t--)
{
while(!q.empty())q.pop();
sum=0;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%s",&s);
len=strlen(s);
for(j=0;j<len;j++)
{
if(s[j]==')')
{
if(!c.empty()&&c.top()=='(')
c.pop();
else
c.push(s[j]);
}
else
c.push(s[j]);
}
aa=bb=0;
while(!c.empty())
{
if(c.top()=='(')bb++;
else
aa++;
c.pop();
}
sum+=(len-aa-bb)/2;
now.st=aa;
now.et=bb;
q.push(now);
}
while(!q.empty())
{
now=q.top();
q.pop();
if(q.empty())break;
noww=q.top();
q.pop();
//cout<<"ssss"<<endl;
//("%d %d %d %d\n",now.st,now.et,noww.st,noww.et);
if(min(noww.et,now.st)>min(noww.st,now.et))
swap(now.st,noww.st),swap(now.et,noww.et);
sum+=min(now.et,noww.st);
if(now.et>noww.st)
{
now.et=now.et-noww.st+noww.et;
}
else
{
now.st+=noww.st-now.et;
now.et=noww.et;
}
if(now.et||now.st)
q.push(now);
}
printf("%d\n",sum*2);
}
}
461

被折叠的 条评论
为什么被折叠?



