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 个只含有 '(' 和  ')' 的字符串, 每个“()”对可以销掉并使ans + 2, 这些字符串可以按某种顺序连接起来, 保证结果最大。

题解:每个字符串都可以进行消除"()"的操作来将它变成一个类似于“((((((",   "))))))",  "))))((((", 这样不能在进行抵消操作的串, 经过预处理之后再以以下排序规则将所有串排序, 最后即可得到最大ans。

1.a串的 "(" 大于等于 “)"  且 b 的 ”)“大于等于 "(" 时, a > b

2.a串的 ”)“大于等于 "(" 且 b 的 "(" 大于等于 “)"  时, b > a

3.a串和b串都是 "(" 大于等于 “)" 那么 ”)“ 多的排前边

4.a串和b串都是”)“大于等于 "(" 则"("多的排前边

AC代码:

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
using namespace std;
struct node
{
    int l, r;
}a[100010];
int cmp(node a,node b)
{
    if(a.l <= a.r && b.l > b.r)
        return true;
    if(a.l > a.r && b.l <= b.r)
        return false;
    if(a.l <= a.r && b.l <= b.r)
        return a.l < b.l;
    if(a.l >= a.r && b.l > b.r)
        return a.r > b.r;
}
int main()
{
    int i, j, n, ans, top, num, t;
    char str1[100010], str2[100010];
    scanf("%d", &t);
    while(t--){
        ans = 0;
        scanf("%d", &n);
        for(i = 1;i <= n;i++){
            top = 0, num = 0;
            scanf("%s", str1);
            for(j = 0;j < strlen(str1);j++){
                if(str1[j] == ')' && str2[top] == '(' && top > 0)
                    ans += 1, top -= 1;
                else
                    str2[++top] = str1[j];
            }
                a[i].l = 0;
                a[i].r = 0;
                for(j = 1;j <= top;j++){
                    if(str2[j] == ')')
                        a[i].l += 1;
                    else
                        a[i].r += 1;
                }
            }
            sort(a + 1, a + n + 1, cmp);
            for(i = 2;i <= n;i++){
                num += a[i-1].r;
                if(a[i].l>num){
                    ans += num;
                    num = 0;
                }
                else{
                    ans += a[i].l;
                    num -= a[i].l;
                }
            }
            printf("%d\n", ans * 2);
        }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/lxcxingc/article/details/81272498