hdu 6299 Balanced Sequence

探讨了如何通过重新排列和组合输入的多个由括号组成的字符串,找到可能得到的字符串中最大长度的平衡子序列。该问题涉及字符串处理和排序算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Balanced Sequence

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 973    Accepted Submission(s): 218


 

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

思路:

每个字符串先内部处理,能相互抵消的先抵消。
然后便形成了形如 1.)))((  2.))((((((  3.)))))( 4.(((
然后按照一定顺序对n个字符串排序,
记最后剩下的左括号的数量为l,右括号的数量为r,
r==0 的在前,之后是l>=r的(r小的在先),
然后是l<r的(l大的在先),最后是l==0 的。
交C++,g++会runtime error
代码:

#include<cstdio>
#include<algorithm>
#include<string.h>
using namespace std;
const int maxn=1e5+10;
struct node
{
    int l,r;
}c[maxn];
char t[maxn];
bool cmp(const node &a,const node &b)
{
    if(a.r==0) return 1;
    if(b.r==0) return 0;
    if(a.l>=a.r&&b.l<b.r) return 1;
    if(a.l<a.r&&b.l>=b.r) return 0;
    if(a.l>=a.r&&b.l>=b.r) return a.r<=b.r;
    return a.l>=b.l;
}
int main()
{
    int T;scanf("%d",&T);
    while(T--)
    {
        int ans=0;
        int n;scanf("%d",&n);
        for(int i=0;i<n;i++)
        {
            scanf("%s",&t);
            int len=strlen(t);
            c[i].l=c[i].r=0;
            for(int j=0;j<len;j++)
            {
                if(t[j]=='(') c[i].l++;
                else
                {
                    if(c[i].l) c[i].l--,ans+=2;
                    else c[i].r++;
                }
            }
        }
        sort(c,c+n,cmp);
        int L=0,R=0;
        for(int i=0;i<n;i++)
        {
            if(c[i].r<=L) ans+=c[i].r*2,L-=c[i].r;
            else ans+=2*L,L=0;
            L+=c[i].l;
        }
        printf("%d\n",ans);
    }
    return 0;
}

 

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值