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

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

题意:给出n组括号,找一种排列方法让合法的()情况最多。

思路:(这个题也并不难,没做出来确实很遗憾)就是贪心。

先对每一组合法的合并一下。剩下三种情况  ((((和)))))和)))))(((((

1,把只有“(”的放最左。

2,把只有“)”的方最右。

3,把排序把(多于)的尽量给一个权值尽量左放,相反情况反之。

代码:

来自:https://blog.csdn.net/dllpXFire/article/details/81176347

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+10;
struct node{
    int l,r;
}a[maxn];
char s[maxn],st[maxn];
bool cmp(const node &a,const node&b)
{
    if(a.l<=a.r&&b.l>b.r) //)少(多 > )多(少
        return true;
    if(a.l>a.r&&b.l<=b.r) //)多(少 < )少(多
        return false;
    if(a.r>=a.l&&b.r>=b.l)//)少(多   )少(多
        return a.l<b.l;   //)少的放前面
    return a.r>b.r;       //(多的优先
}
int t,n;
int main()
{
    //freopen("in.txt","r",stdin);
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        int ans=0;
        for(int i=1;i<=n;i++)
        {
            scanf("%s",s);
            int len=strlen(s),top=0;
            for(int j=0;j<len;j++)
            {
                if(s[j]==')'&&top>0&&st[top]=='(')
                {
                    ans++;
                    top--;
                }
                else st[++top]=s[j];
            }
            a[i].l=a[i].r=0;
            for(int j=1;j<=top;j++)
            if(st[j]=='(')
                a[i].l++;
            else a[i].r++;
        }
        sort(a+1,a+n+1,cmp);
        int num=0;
        for(int i=2;i<=n;i++)
        {
            num+=a[i-1].r;
            if(a[i].l>num)
            {
                ans+=num;
                num=0;
            }
            else
            {
                ans+=a[i].l;
                num-=a[i].l;
            }
        }
        printf("%d\n",ans*2);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/snayf/article/details/81210986