HDU 6299 Balanced Sequence(贪心)

Balanced Sequence

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


 

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

题意:给你若干个括号序列,随意排列组合,求最长的合法序列长度。合法序列题目中已经定义。

实际上我们按照能匹配的括号最多规律进行排序。然后相同的按l小的放前面即可。

具体见代码:

#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn=1e6+10;
int n,m,k;
int ans,tmp,cnt;
int top;
struct node{
int l,r;
node(){}
node(int s,int t){l=s;r=t;}
bool operator<(node aa)const
{
    return min(l,aa.r)>min(aa.l,r)||min(l,aa.r)==min(aa.l,r)&&l>aa.l;
}
}a;
char stk[maxn],s[maxn];
int main()
{
    int T,cas=1;
    scanf("%d",&T);
    while(T--)
    {
        priority_queue<node>q;
        scanf("%d",&n);
        top=-1; ans=0;
        for(int i=0;i<n;i++)
        {
            scanf("%s",s);
            int len=strlen(s);
            for(int j=0;j<len;j++)
            {
                char ch=s[j];
                if(top>=0&&ch==')'&&stk[top]=='(')
                {
                    top--;
                    ans++;
                }
                else stk[++top]=ch;
            }
            int al=0,ar=0;
            while(top>=0)
            {
                if(stk[top]==')')al++;
                else ar++;
                top--;
            }
            q.push(node(al,ar));
        }
        while(!q.empty())
        {
            node pre=q.top();q.pop();
            if(q.empty())break;
            node now=q.top();q.pop();
            if(pre.r>=now.l)
            {
                ans+=now.l;
                pre.r-=now.l;
                pre.r+=now.r;
            }
            else
            {
                ans+=pre.r;
                pre.l+=now.l-pre.r;
                pre.r=now.r;
            }
            if(pre.l||pre.r) q.push(pre);
        }
        printf("%d\n",ans*2);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/LSD20164388/article/details/81178997