• Codeforces 3D


    题目链接

    D. Least Cost Bracket Sequence
    time limit per test
    1 second
    memory limit per test
    64 megabytes
    input
    standard input
    output
    standard output

    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 ai and bi (1 ≤ ai,  bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — 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.

    Sample test(s)
    input
    (??)
    1 2
    2 8
    output
    4
    ()()

     Accepted Code:

     1 from heapq import *
     2 
     3 s = list(raw_input());
     4 ans, heap = 0, [];
     5 b = 0
     6 for i, v in enumerate(s):
     7       if v == '(': 
     8         b += 1
     9     elif v == ')': 
    10           b -= 1
    11     else :
    12           b -= 1;
    13         x, y = map(int, raw_input().split());
    14         ans += y;
    15         s[i] = ')'
    16         heappush(heap, (x-y, i));
    17     if b < 0:
    18           if (not heap):
    19               print -1
    20             quit()
    21         b += 2;
    22         x, y = heappop(heap);
    23         ans += x;
    24         s[y] = '(';
    25 if b: 
    26     print '-1';
    27 else :
    28     print ans
    29     print ''.join(s)
  • 相关阅读:
    linux g++编译dxf文件C++解析库dxflib
    linux g++使用总结
    一个使用three.js的网页DXF文件查看器dxf viewer
    node.js教程基础:node.js访问操作系统
    node.js教程基础:node.js全局对象
    node.js教程基础:node.js命令行选项
    node.js教程基础:node.js包管理器
    node.js教程基础:node.js REPL
    node.js教程基础:第一个node.js程序
    node.js教程基础:node.js安装
  • 原文地址:https://www.cnblogs.com/Stomach-ache/p/3855696.html
Copyright © 2020-2023  润新知