hdu6299,hdu多校第一场

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 ) )(

扫描二维码关注公众号,回复: 9689739 查看本文章
 

Sample Output

 

4 2

题意:给你n个只包含‘(‘’和‘)’的字符串,将这些字符串重新排序连接,问最多有多少个规范的括号(),可以不连续

思路:贪心,先把规范的去掉,剩下的就是))((这种形式,关键在于排序方法,先排r<l(其中r表示右括号,l表示左括号),若r一样则使l大的在前面,否则r小的在前面,l==r放在中间即可,r>l,就相反。要使左括号尽量多的在左边,右括号尽量多的在右边

#include<bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define pb push_back
using namespace std;
const int inf=0x3f3f3f3f;
const int N=100000+10;
const double eps=1e-15;
const int mod=1e9+7;
typedef pair<int,int> P;
struct node
{
    int l,r;
    friend bool operator<(node w,node ww)
    {
        if(w.r<w.l&&ww.r<ww.l)
        {
            if(w.r==ww.r)
                return w.l>ww.l;
            return w.r<ww.r;
        }
        else if(w.r>w.l&&ww.r>ww.l)
        {
            if(w.l==ww.l)
                return w.r<ww.r;
            return w.l>ww.l;
        }
        else if(w.r==w.l&&ww.r==ww.l)
            return w.l<ww.l;
        return w.l-w.r>ww.l-ww.r;
    }
}a[N];
char s[N];
int main()
{
    int t,n;
    scanf("%d",&t);
    while(t--)
    {
        int sum=0;
        scanf("%d",&n);
        for(int k=1;k<=n;k++)
        {
            scanf("%s",s);
            int l=strlen(s);
            int x=0,y=0;
            for(int i=0;i<l;i++)
            {
                if(s[i]=='(')
                    x++;
                else if(s[i]==')'&&x>0)
                    x--;
                else if(s[i]==')'&&x==0)
                    y++;
            }
            sum+=l-x-y;
            a[k].l=x;
            a[k].r=y;
        }
        sort(a+1,a+n+1);
        int x=0,y=0,ans=0;
        for(int i=1;i<=n;i++)
        {
            ans+=a[i].l+a[i].r;
            y+=a[i].r;
            int t=min(x,a[i].r);
            y-=t;
            x-=t;
            x+=a[i].l;
        }
        printf("%d\n",sum+ans-x-y);
    }
}
发布了10 篇原创文章 · 获赞 1 · 访问量 354

猜你喜欢

转载自blog.csdn.net/hl_1997/article/details/81183734
今日推荐