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)

 

你可能感兴趣的:(codeforces)