HDU 多校对抗赛 B Balanced Sequence
Balanced Sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1320 Accepted Submission(s): 316
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.
+ 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.
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组括号字符串,你可以对着n组字符串进行交换顺序后的首尾拼接,求拼接后最大的balance串长度
balance 串 在题目中的定义就是 () 、(())、()()之类的
题解:记录左括号和右括号的数量,按照左括号大小排序,依次拼接,每次拼接找到最优的拼接方法,O(n)扫一遍即可
代码如下:
#include <cstdio> #include <cstring> #include <algorithm> #include <iostream> #include <queue> using namespace std; typedef long long ll; const int maxn = 1e5+5; struct node{ int l,r; }a[maxn]; bool cmp(node a,node b){ if(a.l==b.l) return a.r<b.r; return a.l<b.l; } int ans[maxn]; int vis[maxn]; int main(){ int T; scanf("%d",&T); while(T--){ int n,m; memset(vis,0,sizeof(vis)); scanf("%d%d",&n,&m); for(int i=1;i<=m;i++){ scanf("%d%d",&a[i].l,&a[i].r); } sort(a+1,a+m+1,cmp); priority_queue<int,vector<int>,greater<int> >q; for(int i=1; i<=n; i++){ ans[i]=1;vis[i]=0; q.push(i); } int l=a[1].l,r=a[1].l; for(int i=1;i<=m;i++){ for(;l<a[i].l;l++){ if(vis[l]) q.push(ans[l]); } for(;r<=a[i].r;r++){ if(r>=a[i].l){ ans[r]=q.top();q.pop(); vis[r]=1; } } } for(int i=1; i<=n; i++) { printf("%d",ans[i]); if(i==n) printf("\n"); else printf(" "); } } }
每一个不曾刷题的日子
都是对生命的辜负
从弱小到强大,需要一段时间的沉淀,就是现在了
~buerdepepeqi