hdu 6299 Balanced Sequence

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
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 rint main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int n,ans=0;
        scanf("%d",&n);
        for(int i=0; iscanf("%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; iint tmp=min(po[i].r,c);
            ans+=2*tmp;
            c=c-tmp+po[i].l;
        }
        printf("%d\n",ans);
    }
}

你可能感兴趣的:(STL)