CF3D Least Cost Bracket Sequence TJ

题目链接

思路

贪心法,先将所有的 (?) 设置为 ()) ,然后进行括号匹配,如果不匹配,则查找前面最优的 ()) 换成 (() ,对此我们可以用一个堆来维护。

代码

#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
const int MAXN = 5e4 + 10;
struct node {
    int val;
    int ind;
    bool operator < (const node &x) const {
        return val > x.val;
    }
}a[MAXN];
priority_queue <node > p;
char s[MAXN];
int n = 0 ,lens ,sum = 0;
long long ans = 0;
int main () {
    scanf ("%s",s);
    lens = strlen (s);
    for (int q = 0;q < lens;++ q) {
        if (ans == -1) break;
        if (s[q] == '?') {
            sum --;
            int l ,r;
            scanf ("%d%d",&l ,&r);
            a[++ n].ind = q ,a[n].val = l - r;
            p.push(a[n]);
            s[q] = ')';
            ans += r;
        }
        else if (s[q] == '(') {
            sum ++;
        }
        else {
            sum --;
        }
        if (sum < 0) {
            if (p.empty()) {
                ans = -1;
            }
            if (ans != -1) {
                sum += 2;
                node x = p.top(); p.pop();
                s[x.ind] = '(';
                ans += x.val;
            }
        }
    }
    if (sum != 0)
       ans = -1;
    printf ("%I64d
",ans);
    if (ans != -1) {
        printf ("%s
",s);
    }
    return 0;
}
cb
原文地址:https://www.cnblogs.com/tuscjaf/p/13881254.html