zoukankan      html  css  js  c++  java
  • 3A Least Cost Bracket Sequence —— 贪心

    题解

    This is yet another problem on regular bracket sequences.

    A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.

    For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.

    Input

    The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers a i and b i (1 ≤ a i,  b i ≤ 106), where a i is the cost of replacing the i-th character "?" with an opening bracket, and b i — with a closing one.

    Output

    Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second.

    Print -1, if there is no answer. If the answer is not unique, print any of them.

    Examples

    Input

    (??)
    1 2
    2 8
    

    Output

    4
    ()()
    

    题解

    解题思路

    这道题应用了贪心的思想
    为了方便计算,将?改为)
    借鉴括号匹配的思想,遇到(,计数器++, 遇到)计数器--
    当计数器<0时就要将前面可以改变的)变成(,
    在改变的时候找到x-y最小的,这里用优先队列优化
    最后如果计数器没有归零,那括号就不能匹配完成

    代码

    #include <cstdio>
    #include <cstring>
    #include <queue>
    #define ll long long
    using namespace std;
    const int N = 5e4+5;
    priority_queue<pair<int, int>> q;
    char c[N], c2[N];
    int n, s;
    ll ans;
    int main() {
        scanf("%s", c);
        n = strlen(c);
        for(int i = 0; i < n; i++) {
            if (c[i] == '(') c2[i] = '(', s++;
            else {
                c2[i] = ')'; s--;
                if (c[i] == '?') {
                    int x, y;
                    scanf("%d%d", &x, &y);
                    ans += (ll)y;
                    q.push(make_pair(y - x, i));
                }
                if (s < 0) {
                    if (q.empty()) return puts("-1"), 0;
                    s += 2;
                    ans += (ll)-q.top().first;
                    c2[q.top().second] = '(';
                    q.pop();
                }
            }
        }
        if (s != 0) puts("-1");
        else printf("%lld
    %s", ans, c2);
        return 0;
    }
    
  • 相关阅读:
    Cookie和Session的区别
    get和post的区别
    TCP和UDP的区别
    TCP三次握手过程
    docker 安装prometheus
    大数据集群环境搭建之一 hadoop-ha高可用安装
    大数据集群环境 zookeeper集群环境安装
    Centos 脚本中几个特殊符号的作用笔记
    VMware 设置虚拟机Centos 上网的两种方式
    大数据集群环境搭建之一 Centos基本环境准备
  • 原文地址:https://www.cnblogs.com/shawk/p/12912217.html
Copyright © 2011-2022 走看看