1. 程式人生 > >杭電多校第一場補題-1002 Balanced Sequence

杭電多校第一場補題-1002 Balanced Sequence

names tar clas n) 遇見 include per 不為 return

1002: Balanced Sequence

題意:給定n個字符串,n的大小在1e5左右,字符串的長度也是1e5,字符串僅由‘(’或‘)’組成,合法串可以不是連續的,將這n個串按照一定的順序排列起來,使得組合之後的字符串的合法串的長度最長。n*len的大小是1e6

思路:首先n*len的處理出來每一個字符串中合法的長度,處理的辦法可以參考之前棧的想法,每遇見一個‘)‘,就判斷前面‘(’的個數,只要不為0,此時就可以合成一個合法串,處理完之後可以得到剩下的‘)’和‘(’的個數,然後所有的n個串進行排序,最後將這些))((())((。。。。。))(((的串連接起來即可,排序的方式是)少(多的放在前面,反之放在後面,如果差不多的話,就根據))排序。

代碼如下:

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>

using namespace std;

const int maxn = 100005;

int t;
int n;
char s[maxn];

struct NODE
{
    int l;
    int r;
    int sum;

    bool operator < (const NODE &b) const
    {
        if(l>=r && b.l<=b.r)
            
return false; else if(l<=r && b.l>=b.r) return true; else if(l>=r && b.l>=b.r) return r>=b.r; else if(l<=r && b.l<=b.r) return l<=b.l; } } node[maxn]; int main() { scanf("%d", &t);
while( t-- ) { scanf("%d", &n); for(int cnt=0; cnt<n; cnt++) { scanf("%s", s); int len = strlen(s); node[cnt].l = node[cnt].r = node[cnt].sum = 0; for(int i=0; i<len; i++) { if(s[i] == )) { if(node[cnt].r > 0) { node[cnt].r --; node[cnt].sum ++; } else { node[cnt].l++; } } else { node[cnt].r++; } } } sort(node, node+n); int ans; int now; ///now記錄現在有多少個‘(’ ans = now = 0; for(int i=0; i<n; i++) { ans += node[i].sum; if(node[i].l >=now) { ans += now; now = node[i].r; } else { ans += node[i].l; now -= node[i].l; now += node[i].r; } } printf("%d\n", ans*2); } return 0; }

杭電多校第一場補題-1002 Balanced Sequence