2018 Multi-University Training Contest 1 ------ 1002 hdu6299 Balanced Sequence【贪心】
Balanced Sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2802 Accepted Submission(s): 700
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
#include<bits/stdc++.h>
#include<vector>
using namespace std;
struct node{
int a, b, c;
}sss[100005];
char ss[100005];
vector<node> v1,v2,v3;
bool cmp(node aa, node bb){
if(aa.c >= 0 && bb.c >= 0){
return aa.b < bb.b;
}else if(aa.c >= 0){
return 1;
}else if(bb.c >= 0){
return 0;
}else {
return aa.a > bb.a;
}
}
stack<char> s;
int main() {
int t;
scanf("%d", &t);
while(t--){
int n;
scanf("%d", &n);
int ans = 0;
v1.clear();
v2.clear();
v3.clear();
for(int i = 0; i < n; i++){
scanf("%s",ss);
for(int j = 0; j < strlen(ss); j++){
if(j == 0){
s.push(ss[j]);
}else if(ss[j] == '('){
s.push('(');
}else {
if(!s.empty() && s.top() == '('){
s.pop();
ans++;
}else {
s.push(')');
}
}
}
sss[i].a = 0;
sss[i].b = 0;
while(!s.empty()){
if(s.top() == '('){
sss[i].a++;
s.pop();
}else {
sss[i].b++;
s.pop();
}
}
sss[i].c = sss[i].a - sss[i].b;
}
for(int i = 0; i < n; i++){
if(sss[i].a > 0 && sss[i].b == 0){
v1.push_back(sss[i]);
}else if(sss[i].b > 0 && sss[i].a == 0){
v3.push_back(sss[i]);
}else {
v2.push_back(sss[i]);
}
}
int l = 0;
for(int i = 0; i < v1.size(); i++){
l += v1[i].a;
}
if(v2.size() > 1)
sort(v2.begin(), v2.end(), cmp);
for(int i = 0; i < v2.size(); i++){
int tmp = min(l,v2[i].b);
l -= tmp;
ans += tmp;
l += v2[i].a;
}
for(int i = 0; i < v3.size(); i++){
int tmp = min(l,v3[i].b);
ans += tmp;
l -= tmp;
if(l == 0){
break;
}
}
printf("%d\n", 2*ans);
}
return 0;
}