首页 技术 正文
技术 2022年11月21日
0 收藏 556 点赞 4,046 浏览 1750 个字

D. Least Cost Bracket Sequence

题目连接:

http://www.codeforces.com/contest/3/problem/D

Description

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 Input

(??)

1 2

2 8

Sample Output

4

()()

Hint

题意

给你一个括号序列

有问号的地方给你把该问号变成左括号或者右括号的代价。

然后问你最少多少花费可以使得这个序列变得合法。

如果不能的话,输出-1.

题解:

直接暴力扫一遍。

先把全部问号变成右括号,如果当前这个位置的括号值小于0的话,就把y-x最大的那个位置变回左括号就好了。

用一个优先队列维护就好了。

代码

#include<bits/stdc++.h>
using namespace std;priority_queue<pair<long long,int> >Q;
string s;
int main()
{
cin>>s;
if(s.size()%2==1)return puts("-1"),0;
int now=0;
long long ans=0;
for(int i=0;i<s.size();i++)
{
if(s[i]=='(')
now++;
else if(s[i]==')')
now--;
else
{
int x,y;scanf("%d%d",&x,&y);
now--;s[i]=')';ans+=y;
Q.push(make_pair(y-x,i));
}
if(now<0)
{
if(Q.size()==0)break;
pair<int,int> a = Q.top();Q.pop();
ans-=a.first;s[a.second]='(';
now+=2;
}
}
if(now!=0)return puts("-1"),0;
cout<<ans<<endl;
cout<<s<<endl;
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,904
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,430
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,247
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,058
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,690
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,727