题目:https://acm.hdu.edu.cn/showproblem.php?pid=6299
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
题意理解错了。。以为是要合法的括号匹配,,,看了大佬的代码。。卡在最后处理剩余括号的部分卡了半个多小时。。
AC代码:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <algorithm>
using namespace std;
//最长平衡子序列长度(不连续),又没看懂题
const int N = 100010;
string str[N];
pair<int,int> bracket[N];
int cmp(pair<int,int> a,pair<int,int> b){
return a.first > b.first;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
int t;
cin >> t;
while(t--){
int n; cin >> n;
int ans = 0;
for(int i = 0;i<n;i++){ //这部分先把所有匹配的括号找出来,已经每个字符串剩余的括号也找出来
cin >> str[i];
bracket[i].first = bracket[i].second = 0;
for(int j = 0;j<str[i].size();j++){
if(str[i][j] == '(')
bracket[i].first++;
else{
if(bracket[i].first != 0){
bracket[i].first--,ans++;
}else{
bracket[i].second++;
}
}
}
}
sort(bracket,bracket+n,cmp); //按剩余的左括号数从大到小排序
int l = 0,r = 0;
for(int i = 0;i<n;i++){
int ln = min(l,bracket[i].second);//前一个左括号数,和当前的右括号比较
int rn = min(r,bracket[i].first); //前一个右括号数,和当前的左括号比较
if(ln > rn){ //第一种情况得多
ans += ln; //加上匹配掉的ln对括号
l -= ln; //减去匹配掉的括号
bracket[i].second -= ln;//减去匹配掉的括号
}else{ //第二种情况匹配得多
ans += rn; //加上匹配掉的rn对括号
r -= rn; //减去品牌掉的右括号
bracket[i].first -= rn; //减去品牌掉的括号
}
l += bracket[i].first; //加上剩余的左括号
r += bracket[i].second; //加上剩余的右括号
}
printf("%d\n",ans*2); //括号长度要乘2
}
system("pause");
return 0;
}