杭电多校第一场 Balanced Sequence

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

 

 

Source

2018 Multi-University Training Contest 1

 

 

Recommend

liuyiding   |   We have carefully selected several similar problems for you:  6318 6317 6316 6315 6314 

#include

using namespace std;

const int MAXN = 100000 + 10;

struct f
{
    int l;
    int r;
    int ans;
}a[MAXN];
//加等号
int com(f u , f v)
{
    if(u.r >= u.l && v.r <= v.l)
        return 0;
    if(u.r <= u.l && v.r >= v.l)
        return 1;
    if(u.r < u.l && v.r < v.l)
        return u.r < v.r;
    else
        return u.l > v.l;
}
int main()
{
    int T;
    char q[MAXN];
    scanf("%d", &T);
    while(T --)
    {
        int n ;
        scanf("%d", &n);
        for(int i = 1; i <= n; i ++)
        {
            scanf("%s", q);
            int len = strlen(q);
            a[i].l = a[i].r = a[i].ans = 0;
            for(int j = 0; j < len ; j ++)
            {
                if(q[j] == '(')
                    a[i].l ++;
                else
                {
                    if(a[i].l > 0)
                    {
                        a[i].l --;
                        a[i].ans ++;
                    }
                    else
                        a[i].r ++;
                }
            }
        }
        sort(a + 1, a + n + 1, com);
        int ans = 0, now = 0;
        for(int i = 1; i <= n; i ++)
        {
            if(a[i].r > now)
            {
                a[i].ans += now;
                now = 0;
            }
            else
            {
                a[i].ans += a[i].r;
                now -= a[i].r;
            }
            ans += a[i].ans;
            now += a[i].l;
        }
        printf("%d\n", ans * 2);
    }
    return 0;
}

 

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