Balanced SequenceProblem 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个只包含‘(‘’和‘)’的字符串,将这些字符串重新排序连接,问最多有多少个规范的括号(),可以不连续
思路:贪心,先把规范的去掉,剩下的就是))((这种形式,关键在于排序方法,先排r<l(其中r表示右括号,l表示左括号),若r一样则使l大的在前面,否则r小的在前面,l==r放在中间即可,r>l,就相反。要使左括号尽量多的在左边,右括号尽量多的在右边
#include<bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define pb push_back
using namespace std;
const int inf=0x3f3f3f3f;
const int N=100000+10;
const double eps=1e-15;
const int mod=1e9+7;
typedef pair<int,int> P;
struct node
{
int l,r;
friend bool operator<(node w,node ww)
{
if(w.r<w.l&&ww.r<ww.l)
{
if(w.r==ww.r)
return w.l>ww.l;
return w.r<ww.r;
}
else if(w.r>w.l&&ww.r>ww.l)
{
if(w.l==ww.l)
return w.r<ww.r;
return w.l>ww.l;
}
else if(w.r==w.l&&ww.r==ww.l)
return w.l<ww.l;
return w.l-w.r>ww.l-ww.r;
}
}a[N];
char s[N];
int main()
{
int t,n;
scanf("%d",&t);
while(t--)
{
int sum=0;
scanf("%d",&n);
for(int k=1;k<=n;k++)
{
scanf("%s",s);
int l=strlen(s);
int x=0,y=0;
for(int i=0;i<l;i++)
{
if(s[i]=='(')
x++;
else if(s[i]==')'&&x>0)
x--;
else if(s[i]==')'&&x==0)
y++;
}
sum+=l-x-y;
a[k].l=x;
a[k].r=y;
}
sort(a+1,a+n+1);
int x=0,y=0,ans=0;
for(int i=1;i<=n;i++)
{
ans+=a[i].l+a[i].r;
y+=a[i].r;
int t=min(x,a[i].r);
y-=t;
x-=t;
x+=a[i].l;
}
printf("%d\n",sum+ans-x-y);
}
}