Balanced Sequence

http://acm.hdu.edu.cn/showproblem.php?pid=6299

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

题意:

进行括号匹配,将N个段随意组合,然后进行括号匹配。问最多可以匹配多少括号

分析:

先用栈进行预处理,将n个段最后化简为a个 " ) " 和b个“(”,然后用优先队列优先处理min(a,b)的较大的两组实现贪心,然后将新产生的加入队列。。。

代码:

#include
using namespace std;
char s[100005];
struct node
{
    int st,et;
    bool operator<(const node &aa)const
    {
        return min(st,et)q;
stackc;
int main()
{
    int t,i,j,len,sum,aa,bb,tt,n;
    node now,noww;
    scanf("%d",&t);
    while(t--)
    {
        while(!q.empty())q.pop();
        sum=0;
        scanf("%d",&n);
        for(i=0;imin(noww.st,now.et))
                swap(now.st,noww.st),swap(now.et,noww.et);
            sum+=min(now.et,noww.st);
            if(now.et>noww.st)
            {
                now.et=now.et-noww.st+noww.et;
            }
            else
            {
                now.st+=noww.st-now.et;
                now.et=noww.et;
            }
            if(now.et||now.st)
            q.push(now);
        }
        printf("%d\n",sum*2);
    }
}

 

 

你可能感兴趣的:(贪心)