Balanced Sequence ( 括号最大匹配个数)

Chiaki has nn strings s1,s2,…,sns1,s2,…,sn consisting of '(' and ')'. A string of this type is said to be balanced: 

+ if it is the empty string 
+ if AA and BB are balanced, ABAB is balanced, 
+ if AA is balanced, (A)(A) is balanced. 

Chiaki can reorder the strings and then concatenate them get a new string tt. Let f(t)f(t) be the length of the longest balanced subsequence (not necessary continuous) of tt. Chiaki would like to know the maximum value of f(t)f(t) for all possible tt. 

Input

There are multiple test cases. The first line of input contains an integer TT, indicating the number of test cases. For each test case: 
The first line contains an integer nn (1≤n≤1051≤n≤105) -- the number of strings. 
Each of the next nn lines contains a string sisi (1≤|si|≤1051≤|si|≤105) consisting of `(' and `)'. 
It is guaranteed that the sum of all |si||si| does not exceeds 5×1065×106. 

Output

For each test case, output an integer denoting the answer. 

Sample Input

2
1
)()(()(
2
)
)(

Sample Output

4
2

 

寻找最大平衡串的长度 

排序是关键

因为剩下的括号最多只有四种情况就是

1.只有(   ((((((((

2.只有)   )))))))

3.(比)多  (((((())

4.)比(多   ))))))(((

然后我们要做的就是把他们排序,既然要得到尽可能多的匹配,那就贪心去排序,每次将(放在前面,把)放在后面,然后排序规则可以这样

1.先把 ( 全放进来

2.把 ( 比 ) 多的串放在前面

3.如果两个串都是 ( 比 ) 多,那就把 ) 少的放在前面

4.如果两个都是 ( 比 ) 少,那就把 ( 多的放在前面

5.最后再把全部都是 ) 的放在后面。

然后在扫一遍,L记录我扫到这个串的时候还有多少 ( 没有匹配,然后每次尽可能多的拿去匹配掉

 

 

#include
#include
#include
#include
#include
#include
#include
#include 
using namespace std;
long long int sum;
struct ss
{
    int l;
    int r;
    int ans;
}str[100010];
bool cmp (ss x,ss y)
{
    ///')'比'('多的放后面
    if (x.r >= x.l && y.r < y.l)
        return false;
    if (x.r < x.l && y.r >= y.l)
        return true;
    ///')'比'('少   比较')'少的放前面
    /// ')'比'('多   比较'('少的放后面
    if (x.r < x.l && y.r < y.l)
        return x.ry.l;
}
char s[100005];
int main()
{
    int n , t;
    int i , j, k;
    scanf("%d", &t);
    while( t-- )
    {
        sum = 0;
        memset( str, 0, sizeof( str ));
        scanf("%d",&n);
        for( i = 0; i 0 )
                    {
                       str[i].l--;
                       str[i].ans++;
                    }
                    else
                        str[i].r++;
                }
            }
        }
        sort( str, str+n, cmp);
        long long int cnt = 0;
        for( i = 0; i 0 )
            {
                if( str[i].r >= cnt )
                {
                    sum = sum + cnt;
                    cnt = 0 ;
                }
                else
                {
                    sum = sum + str[i].r;
                    cnt  = cnt - str[i].r;
                }
                cnt = cnt+str[i].l;
            }
            else
            {
                cnt = cnt+str[i].l;
            }

        }
        printf("%lld\n", sum*2);
    }
       return 0;
}

你可能感兴趣的:(编程)