hdu6299 2018杭電多校1B Balanced Sequence
題目:
給定
n
n
n個括號序列,第
i
i
i個括號序列為
s
i
s_i
si,要將這
n
n
n個序列重新排個序,然後拼接起來,使拼接成的括號序列的最長括號匹配子序列最長。
(
1
≤
n
≤
1
0
5
,
∑
∣
s
i
∣
≤
5
⋅
1
0
6
)
(1 \le n \le 10^5,\sum |s_i| \le 5 \cdot 10^6)
(1≤n≤105,∑∣si∣≤5⋅106)
題解:
首先考慮一個括號序列的最長括號匹配子序列的長度是怎麼算的,設這個括號序列的長度為
n
n
n,用’(’+1,’)’-1算出的最後的結果為
p
r
e
pre
pre
複雜度: O ( ∑ ∣ s i ∣ l o g ( ∣ ∑ ∣ s i ∣ ∣ ) ) O(\sum |s_i|log(|\sum|s_i||)) O(∑∣si∣log(∣∑∣si∣∣))
程式碼:
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<vector>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<string>
#include<bitset>
#include<sstream>
#include<ctime>
//#include<chrono>
//#include<random>
//#include<unordered_map>
using namespace std;
#define ll long long
#define ls o<<1
#define rs o<<1|1
#define pii pair<int,int>
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define sz(x) (int)(x).size()
#define all(x) (x).begin(),(x).end()
const double pi=acos(-1.0);
const double eps=1e-6;
const int mod=1e9+7;
const int INF=0x3f3f3f3f;
const int maxn=1e5+5;
ll read(){
ll x=0,f=1;
char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
int T,n;
string s[maxn];
pii a[maxn];
int cmp(pii a,pii b){
if(min(a.se,a.fi+b.se)==min(b.se,b.fi+a.se)){
return a.fi>b.fi;
}
return min(a.se,a.fi+b.se)>min(b.se,b.fi+a.se);
}
int main(void){
// freopen("in.txt","r",stdin);
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin>>T;
while(T--){
cin>>n;
int sum=0;
for(int i=1;i<=n;i++){
cin>>s[i];
sum+=(int)s[i].length();
int mn=0,pre=0;
for(int j=0;j<(int)s[i].length();j++){
if(s[i][j]=='(')pre++;
else pre--;
mn=min(mn,pre);
}
a[i].fi=pre;
a[i].se=mn;
}
sort(a+1,a+n+1,cmp);
int pre=0,mn=INF;
for(int i=1;i<=n;i++){
mn=min(mn,pre+a[i].se);
pre+=a[i].fi;
}
cout<<sum-pre+2*min(0,mn)<<endl;
}
return 0;
}