zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    大二暑假学习第一周
    PyQt5+pycharm 中对生成的.py文件无法运行的问题
    尚筹网19总结
    尚筹网19项目部署
    MAC远程连接Linux
    尚筹网17订单、支付
    尚筹网16确认回报、订单
    支付宝沙箱环境
    内网穿透
    支付宝开发平台使用
  • 原文地址:https://www.cnblogs.com/tuscjaf/p/13881254.html
Copyright © 2011-2022 走看看