Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3780 Accepted Submission(s): 991
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
题意: 输入T组案例,每组开头输入n个括号字符串,让你将这些括号字符串组合使得组合成的合法匹配的括号子串长度最多。
题解:什么是合法匹配的括号字串,就是类似如下的这几种:()()() (((((()))))) ()()(((())))
那要如何匹配才能使得匹配的括号最多呢?这里就是一个贪心的思路。在前面的要 左括号尽可能左括号多右括号少(因为已经没有左括号和这些右括号进行匹配),同理在后面的要尽可能使得左边的右括号比右边的左括号多。
我们先用栈来对每个括号字符串进行处理(代码种用力对左括号、右括号、和匹配括号数记数的办法),把匹配的括号去掉。最后出现不匹配的括号字符串只有这种 左边全是右括号右边全是左括号的情况: )))))))))(((((( {其中((((、)))))也算这种情况}
然后对处理后的字符串进行排序,有3种类型的比较,比较出四种情况,详细在代码的cmp函数中。
代码:
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include