HDU - 6299 Balanced Sequence (2018 Multi-University Training Contest 1 B)

版权声明:Why is everything so heavy? https://blog.csdn.net/lzc504603913/article/details/81183214

Balanced Sequence

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2043    Accepted Submission(s): 504


 

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

 

Source

2018 Multi-University Training Contest 1

 

Recommend

liuyiding

 

题意:给你一堆括号序,问你随便排列之后,最长的匹配子串(不连续)。

解题思路:贪心思想。首先计算出所有括号字符串的已匹配长度的和,然后就会剩下一堆)))((((((这样的括号。然后就对这样的括号排序,按照直觉,只要贪心的保证一边的括号最长即可。如:

已知现在剩下的括号序为 ))(

接下来需要操作的括号序为  ))(((

那么肯定是把第一个放第二个右边形成的匹配序长。所以,为了使得左括号尽量在右括号左边,只要按照左括号数量,从大到小排序的贪心处理即可(右括号也行)

#include <bits/stdc++.h>
using namespace std;
const int MAXN=100505;
typedef long long int ll;

pair<int,int> li[MAXN];
bool cmp(pair<int,int> &a,pair<int,int> &b){
    return a.first>b.first;
}

char str[MAXN];
int main()
{
    int T;
    scanf("%d",&T);
    for(int qqq=0;qqq<T;qqq++){
        int N;
        scanf("%d",&N);
        int ans=0;
        for(int i=0;i<N;i++){
            scanf("%s",str);
            li[i].first=li[i].second=0;
            for(int j=0;str[j]!='\0';j++){
                if(str[j]=='(')
                    li[i].second++;
                else{
                    if(li[i].second)
                        li[i].second--,++ans;
                    else
                        li[i].first++;
                }
            }
        }
        sort(li,li+N,cmp);
        int l=0,r=0;
        for(int i=0;i<N;i++){
            int ln=min(l,li[i].second);
            int rn=min(r,li[i].first);
            if(ln>rn){
                ans+=ln;
                l-=ln;
                li[i].second-=ln;
            }
            else{
                ans+=rn;
                r-=rn;
                li[i].first-=rn;
            }
            l+=li[i].first;
            r+=li[i].second;
        }
        printf("%d\n",ans*2);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/lzc504603913/article/details/81183214