zoukankan      html  css  js  c++  java
  • 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)
  • 相关阅读:
    职场中如何沟通 15条技巧现在学
    白领丽人:这六行盛产“钻石王老五”
    个人创业融资中的八大法律问题
    [转帖]用心领导先于理性管理
    职场中牢固人际关系的三十六计
    创业:如何制定最佳融资决策
    工作中如何演绎好你的职场情绪
    怎么成为一个成功的人
    创业不得不看:华商富豪们的成功哲学
    一流简历的10大关注项
  • 原文地址:https://www.cnblogs.com/Stomach-ache/p/3855696.html
Copyright © 2011-2022 走看看