Balanced Sequence

PS:先拿两个试一下,找到了。。。错误的排序方式,于是百度了两种做法。

(1)按照一个串的贡献进行排序,每次优先处理两个贡献大的串,然后用优先队列动态的对每次剩下的串排序。

//#include<bits/stdc++.h>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<bitset>
#include<vector>
#include<queue>
#include<set>
#define ll long long
#define P pair<int, int>
#define PP pair<int,pair<int, int>>
#define pb push_back
#define pp pop_back
#define lson root << 1
#define INF (int)2e9 + 7
#define rson root << 1 | 1
#define LINF (unsigned long long int)1e18
#define mem(arry, in) memset(arry, in, sizeof(arry))
using namespace std;

const int N = 1e5 + 5;

struct node {
    int l, r;
    bool operator < (const node& i) const {
        return min(l, r) < min(i.l, i.r);
    }
}a[N];

int n, T;

int main()
{
    cin >> T;
    while(T--) {
        cin >> n;
        vector<string> S(n + 1);

        for(int i = 1; i <= n; i++) {
            char buf[N];
            scanf("%s", buf);
            S[i] = buf;
        }

        priority_queue<node> q;

        int sum = 0;
        for(int i = 1; i <= n; i++) {
            int mx = 0, d = 0;
            for(auto c : S[i]) {
                d += (c == '(' ? 1 : -1);
                if(d < mx) mx = d;
            }
            a[i].l = -mx;
            a[i].r = d - mx;
            sum += (int)S[i].size() - d + 2 * mx;
            q.push(a[i]);
        }

        node z;
        while(q.size() > 1) {
            node x = q.top(); q.pop();
            node y = q.top(); q.pop();

            if(min(y.r, x.l) > min(y.l, x.r)) swap(x.l, y.l), swap(x.r, y.r);

            int tp = min(x.r, y.l);
            sum += 2 * tp;
            if(x.r >= y.l) {
                z.l = x.l;
                z.r = y.r + (x.r - y.l);
            }
            else {
                z.l = x.l + y.l - x.r;
                z.r = y.r;
            }
            q.push(z);
        }

        printf("%d\n", sum);
    }
    return 0;
}
View Code

(2)暂且不懂

猜你喜欢

转载自www.cnblogs.com/zgglj-com/p/9373970.html