hdu 6299 Balanced Sequence

本文探讨了如何通过重新排序和拼接多个含'('和')'的字符串,以获得最大数量的完整'()'的问题。重点在于根据每串中左括号和右括号的数量进行最优排序,确保左括号尽可能在前,右括号尽可能在后。

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

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

题目大意:n个只含’(’ ‘)’ 的字符串不打乱自身顺序的情况下自由拼接,最后可以得到多少个完整的”()”。
难点在于怎么根据每串多出来的‘(’ ‘)’ 数量排序,要使左括号尽量多的在左边,右括号尽量多的在右边,成为最优解

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1e5+1,INF=0x3f3f3f3f;
const ll mod=1e9+7;
char s[N];
struct node
{
    int l,r;
    bool operator < (const node& s)const//尽量让l多的在前并且保证r尽量的小
    {
        if(l<=r&&s.l>s.r)//左少右多  vs  左多右少
        {
            return false;//false不交换
        }
        if(l>r&&s.l<=s.r)//左多右少  vs  左少右多
        {
            return true;//true交换
        }
        if(r>=l&&s.r>=s.l)//左少右多  vs  左少右多
        {
            return l>s.l;
        }
        return r<s.r;
    }
} po[N];
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int n,ans=0;
        scanf("%d",&n);
        for(int i=0; i<n; i++)
        {
            scanf("%s",s);
            int cl=0,cr=0;
            for(int j=0; s[j]; j++)
            {
                if(s[j]=='(') cl++;
                else
                {
                    if(cl)
                    {
                        cl--;
                        ans+=2;
                    }
                    else cr++;
                }
            }
            po[i].l=cl;
            po[i].r=cr;
        }
        sort(po,po+n);
        int c=po[0].l;
        for(int i=1; i<n; i++)
        {
            int tmp=min(po[i].r,c);
            ans+=2*tmp;
            c=c-tmp+po[i].l;
        }
        printf("%d\n",ans);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值