HDU6299-2018ACM暑假多校联合训练1002-Balanced Sequence

这个题的题意是给你n个字符串,认定()是一种平衡的串,两个以上连续的()()也是一种平衡的串,如果一对括号里面包含一个平衡的串,这个括号也被算在这个平衡的串之内,
如(()(()))是一个长度为8的平衡字符串,让你通过对给的n个串进行排序,组成一个新的串,问其中平衡串的最大长度是多少
这个题的重点是在对这些串排序规则的制定(本鶸连要排序都想不到)
如果要得到一个最长平衡串的串
需要遵循以下几点规则
注:左为'(',右为')'
1.左多右少的串在右多左少的左边
2.左少右多和左少右多排序时,左括号少的放在右边
3.其他情况按右边少的放在左边
 
这个题最重要的一点是要知道 左括号可以一直用下去,而右括号在匹配到下一个串时就失效了,所以要尽可能多的利用右括号
左右相等的其实放在左多右少和右多左少里面都可以
 
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 <iostream>
#include <algorithm>
#include <string.h>
#include <math.h> using namespace std; struct node
{
int l, r;
node() {}
node(int a, int b) { l = a, r = b; }
bool operator < (const node &a) const
{
if (r >= l && a.r >= a.l)
return l>a.l;
else if (l > r && a.l <= a.r)
return true;
else if (l <= r && a.l > a.r)
return false;
else
return r < a.r;
}
}node[]; int main()
{
int t;
scanf("%d", &t); while (t--)
{
int n;
long long num = ;
scanf("%d", &n);
char ch[];
for (int i = ; i < n; i++)
{
scanf("%s", ch);
int len = strlen(ch);
int l = , r = ;
for (int j = ; j < len; j++)
{
if (ch[j] == '(')
l++;
else
{
if (l)
{
l--;
num += ;
}
else
r++;
} node[i].l = l;
node[i].r = r;
}
}
sort(node, node + n);
//for (int i = 0; i < n; i++)
//cout << node[i].l << ends << node[i].r << endl;
int l = ;
for (int i = ; i < n; i++)
{
int r = node[i].r;
if (l&&r)
{
int x = min(l, r);
num += x * ;
l -= x;
}
l += node[i].l;
}
cout << num << endl;
}
return ;
}
上一篇:LPC1768/1769之CAN控制器概述(附库函数下载地址)


下一篇:Java经典编程题50道之五十