2018杭電多校day1_B Balanced Sequence HDU - 6299

Chiaki has nn strings s1,s2,…,sns1,s2,…,sn consisting of '(' and ')'. A string of this type is said to be balanced: 

+ if it is the empty string 
+ if AA and BB are balanced, ABAB is balanced, 
+ if AA is balanced, (A)(A) is balanced. 

Chiaki can reorder the strings and then concatenate them get a new string tt. Let f(t)f(t)be the length of the longest balanced subsequence (not necessary continuous) of tt. Chiaki would like to know the maximum value of f(t)f(t) for all possible tt. 

Input

There are multiple test cases. The first line of input contains an integer TT, indicating the number of test cases. For each test case: 
The first line contains an integer nn (1≤n≤1051≤n≤105) -- the number of strings. 
Each of the next nn lines contains a string sisi (1≤|si|≤1051≤|si|≤105) consisting of `(' and `)'. 
It is guaranteed that the sum of all |si||si| does not exceeds 5×1065×106. 

Output

For each test case, output an integer denoting the answer. 

Sample Input

2
1
)()(()(
2
)
)(

Sample Output

4
2

這是後來補的題,當時似乎在卡別的題,根本沒有看到這個題,賽後聽dls講解似乎是挺簡單的貪心的。

題意:給n個括號串,把他們拼接起來看有多少合法括號。

思路:貪心思路 ,儘量使排序後前面'('多,後面')'多 ,在輸入每個串的時候先進行預處理把已經合法的()計數。然後排序後,記錄當前左括號數量,更新右括號數量,當前合法()數量,當前左括號數量。

//看了很多題解,裏面的結構體排序都用到重載運算符...看樣子是差的太遠了。回頭要補一下重載運算符這種操作。。。。。

//感覺結構體排序重載運算符其實就和自己手寫cmp函數一樣?具體也不是很清楚,記錄下,近期補習一下。

 

代碼:

#include<bits/stdc++.h>

#include<cstdio>
#include<cstring>
#include<queue>
#define ms(a,x) memset(a,x,sizeof(a))
using namespace std;

#define N 200
#define MAX 200000
const int maxn=5e5+1000;
//B
struct note
{
    int l,r;
    int rs;
    bool operator <(const note &p) const//儘量使排序後前面'('多,後面')'多
    {
         if(r>=l&&p.l>p.r) return 0;
         if(l>r&&p.r>=p.l) return 1;
         if(r>=l&&p.r>=p.l) return l>p.l;
         return p.r>r;
    }
}aa[maxn];

int t,n;
char ss[maxn];
int main(){
	scanf("%d",&t);
	while(t--){
		scanf("%d",&n);
		getchar();
		for(int i=1;i<=n;i++){
			aa[i].l=aa[i].r=aa[i].rs=0;
			scanf("%s",ss);
			int len=strlen(ss);
			for(int j=0;j<len;j++){
				if(ss[j]=='(')aa[i].l++;
				else {
					if(aa[i].l>0){
						aa[i].l--;
						aa[i].rs++;
					}else aa[i].r++;
				}
				
			}
		}
		
		sort(aa+1,aa+1+n);
		
		int ans=0;
		int nowl=0;
		for(int i=1;i<=n;i++){
			if(aa[i].r>nowl)aa[i].r=nowl;
			ans+=aa[i].r+aa[i].rs;
			nowl+=aa[i].l;
			nowl-=aa[i].r;
		}
		printf("%d\n",ans*2);
	}
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章