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;
    }
    
  • 相关阅读:
    嵌入式linux调试技术
    HAL
    让开发板发出声音: 蜂鸣器驱动
    LED 将为我闪烁: 控帘 j发光二级管
    第一个Linux驱动程序: 统计单词个数
    搭建 S3C6.410 开发板的 测试环境
    第四章源代码的下载和编译读后感
    第三章Git使用入门读后感
    第二章搭建安卓开发环境读后感
    第一章安卓系统移植和驱动开发读后感
  • 原文地址:https://www.cnblogs.com/Z8875/p/12912217.html
Copyright © 2011-2022 走看看