hdu多校训练赛第一场 B Balanced Sequence

B Balanced Sequence
题 意:给你n串长度为s的字符串,只包含’(‘和’)’。你可以重新排序这些字符串,凑出最长的平衡串。不连续也可以,什么是平衡串呢?
+ if it is the empty string
+ if A and B are balanced, AB is balanced,
+ if A is balanced, (A) is balanced.
数据范围:
1<=t<=1e5
1<=|si|<=1e5
It is guaranteed that the sum of all |si| does not exceeds 5×1e6
输入样例:

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

输出样例:

4
2

思 路:先把已经符合要求的段去除。发现最后只会剩下,三种序列(,),)(这三种。
然后贪心排序。贪心思想是什么呢?越在左边‘(’经可能多,’)’经可能少。怎么排序呢,左括号为1,右括号为-1.按左括号加右括号的贡献度排序。

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>
#include <set>
#include <stack>
#define N 1000005
#define rep(i,a,n) for(int i=a;i<n;i++)
#define per(i,a,n) for(int i=n-1;i>=a;i++)
using namespace std;
typedef long long ll;
const int maxn = 1e5+5;
char s[maxn];
int n;
int ans;
stack<char> st;
struct node{
    int x,y;
}a[maxn];
vector<node> v1,v2,v3;
void init(){
    ans = 0;
    while(st.size())st.pop();
    v1.clear();
    v2.clear();
    v3.clear();
    for(int i=0;i<maxn;i++){
        a[i].x = 0;
        a[i].y = 0;
    }
}
bool cmp(node p,node q){
    if(p.x + p.y >=0 && q.x+q.y >=0) return p.y > q.y;
    else if(p.x + p.y>=0) return true;
    else if(q.x + q.y>=0) return false;
    else return p.x > q.x;
}
int main() {
    int t;
    scanf("%d",&t);
    while(t--){
        init();
        scanf("%d",&n);
        for(int i=0;i<n;i++){
            scanf("%s",s);
            int len = strlen(s);
            for(int j=0;j<len;j++){
                if(s[j] == '(')st.push(s[j]);
                else if(st.size() && st.top() == '('){
                    ans++;
                    st.pop();
                }else{
                    st.push(s[j]);
                }
            }
            while(st.size()){
                if(st.top() == '(') a[i].x++;
                else a[i].y--;
                st.pop();
            }
            if(a[i].x && a[i].y == 0) v1.push_back(a[i]);
            else if(a[i].x == 0 && a[i].y) v3.push_back(a[i]);
            else v2.push_back(a[i]);
        }
        sort(v2.begin(),v2.end(),cmp);
        int temp = 0;
        for(int i=0;i<v1.size();i++){
            temp+=v1[i].x;
        }
        for(int i=0;i<v2.size();i++){
            ans+=min(temp,-v2[i].y);
            if(temp + v2[i].y <= 0){
                temp = v2[i].x;
                continue;
            }
            temp+=v2[i].x + v2[i].y;
        }
        for(int i=0;i<v3.size();i++){
            ans+=min(temp,-v3[i].y);
            if(temp + v3[i].y <= 0){
                temp = 0;
                break;
            }
            temp += v3[i].y;
        }
        printf("%d\n",ans*2);
    }
    return 0;
}
/*
3
6 2
1 2
3 6
*/

猜你喜欢

转载自blog.csdn.net/qq_37129433/article/details/81185589