hdu多校1002 Balanced Sequence

2023-02-25,,

Balanced Sequence
Time Limit: / MS (Java/Others) Memory Limit: / K (Java/Others)
Total Submission(s): Accepted Submission(s): 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 (≤n≤) -- the number of strings.
Each of the next n lines contains a string si (≤|si|≤) consisting of `(' and `)'.
It is guaranteed that the sum of all |si| does not exceeds ×. Output
For each test case, output an integer denoting the answer. Sample Input )()(()( )
)( Sample Output Source
Multi-University Training Contest Recommend
liuyiding | We have carefully selected several similar problems for you: Statistic | Submit | Discuss | Note
Home | Top Hangzhou Dianzi University Online Judge 3.0
Copyright © - HDU ACM Team. All Rights Reserved.
Designer & Developer : Wang Rongtao LinLe GaoJie GanLu
Total 0.037002(s) query , Server time : -- ::, Gzip enabled

预处理+贪心

最后剩下的左括号的数量为l,右括号的数量为r,

r==0 的在前,之后是l>=r的(r小的在先),

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<vector>
#include<algorithm>
#include<stack>
using namespace std;
struct node
{
int l,r;
}c[];
char t[];
bool cmp(node a,node b)
{
if(a.r==) return ;
if(b.r==) return ;
if(a.l>=a.r&&b.l<b.r) return ;
if(a.l<a.r&&b.l>=b.r) return ;
if(a.l>=a.r&&b.l>=b.r) return a.r<=b.r;
return a.l>=b.l;
}
//按照没有)
//( > ) 要在 ( < )前面
// 如果都是。就按)小的在前面
//左括号多的在前面
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
int n;
scanf("%d",&n);
int ans=;
for(int i=;i<n;i++)
{
cin>>t; int len=strlen(t);
c[i].l=c[i].r=;
for(int j=;j<len;j++)
{
if(t[j]=='(')
c[i].l++;
else
{
if(c[i].l)
c[i].l--,ans+=;
else
c[i].r++;
}
}
}
sort (c,c+n,cmp); int L=,R=;
for(int i=;i<n;i++)
{
if(c[i].r<=L) ans+=c[i].r*,L-=c[i].r;
else ans+=*L,L=;
L+=c[i].l;
}
printf("%d\n",ans); } return ;
}

hdu多校1002 Balanced Sequence的相关教程结束。

《hdu多校1002 Balanced Sequence.doc》

下载本文的Word格式文档,以方便收藏与打印。