1. 程式人生 > >hdu 6299 Balanced Sequence

hdu 6299 Balanced Sequence

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

題目大意:n個只含’(’ ‘)’ 的字串不打亂自身順序的情況下自由拼接,最後可以得到多少個完整的”()”。
難點在於怎麼根據每串多出來的‘(’ ‘)’ 數量排序,要使左括號儘量多的在左邊,右括號儘量多的在右邊,成為最優解

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1e5+1,INF=0x3f3f3f3f;
const ll mod=1e9+7;
char s[N];
struct node
{
    int l,r;
    bool operator < (const node& s)const//儘量讓l多的在前並且保證r儘量的小
    {
        if(l<=r&&s.l>s.r)//左少右多  vs  左多右少
        {
            return
false;//false不交換 } if(l>r&&s.l<=s.r)//左多右少 vs 左少右多 { return true;//true交換 } if(r>=l&&s.r>=s.l)//左少右多 vs 左少右多 { return l>s.l; } return r<s.r; } } po[N]; int main() { int t; scanf("%d",&t); while(t--) { int n,ans=0; scanf("%d",&n); for(int i=0; i<n; i++) { scanf("%s",s); int cl=0,cr=0; for(int j=0; s[j]; j++) { if(s[j]=='(') cl++; else { if(cl) { cl--; ans+=2; } else cr++; } } po[i].l=cl; po[i].r=cr; } sort(po,po+n); int c=po[0].l; for(int i=1; i<n; i++) { int tmp=min(po[i].r,c); ans+=2*tmp; c=c-tmp+po[i].l; } printf("%d\n",ans); } }