当前位置: 代码迷 >> 综合 >> 2018杭电多校day1_B Balanced Sequence HDU - 6299
  详细解决方案

2018杭电多校day1_B Balanced Sequence HDU - 6299

热度:96   发布时间:2023-11-05 08:25:34.0

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

这是后来补的题,当时似乎在卡别的题,根本没有看到这个题,赛后听dls讲解似乎是挺简单的贪心的。

题意:给n个括号串,把他们拼接起来看有多少合法括号。

思路:贪心思路 ,尽量使排序后前面'('多,后面')'多 ,在输入每个串的时候先进行预处理把已经合法的()计数。然后排序后,记录当前左括号数量,更新右括号数量,当前合法()数量,当前左括号数量。

//看了很多题解,里面的结构体排序都用到重载运算符...看样子是差的太远了。回头要补一下重载运算符这种操作。。。。。

//感觉结构体排序重载运算符其实就和自己手写cmp函数一样?具体也不是很清楚,记录下,近期补习一下。

 

代码:

#include<bits/stdc++.h>#include<cstdio>
#include<cstring>
#include<queue>
#define ms(a,x) memset(a,x,sizeof(a))
using namespace std;#define N 200
#define MAX 200000
const int maxn=5e5+1000;
//B
struct note
{int l,r;int rs;bool operator <(const note &p) const//尽量使排序后前面'('多,后面')'多{if(r>=l&&p.l>p.r) return 0;if(l>r&&p.r>=p.l) return 1;if(r>=l&&p.r>=p.l) return l>p.l;return p.r>r;}
}aa[maxn];int t,n;
char ss[maxn];
int main(){scanf("%d",&t);while(t--){scanf("%d",&n);getchar();for(int i=1;i<=n;i++){aa[i].l=aa[i].r=aa[i].rs=0;scanf("%s",ss);int len=strlen(ss);for(int j=0;j<len;j++){if(ss[j]=='(')aa[i].l++;else {if(aa[i].l>0){aa[i].l--;aa[i].rs++;}else aa[i].r++;}}}sort(aa+1,aa+1+n);int ans=0;int nowl=0;for(int i=1;i<=n;i++){if(aa[i].r>nowl)aa[i].r=nowl;ans+=aa[i].r+aa[i].rs;nowl+=aa[i].l;nowl-=aa[i].r;}printf("%d\n",ans*2);}return 0;
}

 

  相关解决方案