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.

输入:

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.

输出:

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.

样例输入:

(??)
1 2
2 8

样例输出:

4
()()

描述:

这是关于普通括号序列的另一个问题。如果在括号序列中插入“+”和“1”,我们就可以得到一个正确的数学表达式,那么这个括号序列就是规则的。例如,序列"(())()", "()"和"(()(()))"是规则的,然而")(", "(()"和"(()))("就不是。你有由"(", ")"和"?"等符号组成的括号序列的一种模式。你需要用一个括号去替代每一个"?"字符,于是你得到了一个规则的括号序列。

对于每个字符“?”,给出了用“(”和“)”替换它的成本。 在所有可能的变型模式中,你应该选择最便宜的。

输入:

第一行包括一个偶数长度的非空图案,由"(", ")"和"?"字符组成。它的长度不超过5·104。接下来有m行,m是图案中"?"字符的数量。每一行包括两个整数aibi (1 ≤ ai,  bi ≤ 106),其中ai是用开括号替换第i个字符“?”的成本,bi是用闭括号替换的成本。  

输出:

在第一行输出最优且规则的括号序列的成本,并且在第二行输出所需的序列。

如果没有答案,则输出-1。如果答案不唯一,则输出任意一个即可。

样例输入:

(??)
1 2
2 8

样例输出:

4
()()

题目地址链接:Problem - D - Codeforces

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值