# CodeForces 3D Least Cost Bracket Sequence优先队列

431人阅读 评论(0)

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

Input
(??)
1 2
2 8

Output
4
()()
#include<cstdio>
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
char str[50005];
int len,a,b;
struct cost
{
int id,v;
bool operator<(const cost &a)const{return v<a.v;}
};
cost make(int i,int p)
{
cost tmp;
tmp.id=i;
tmp.v=p;
return tmp;
}
priority_queue<cost>m;
int main()
{
//  freopen("cin.txt","r",stdin);
scanf("%s",str);

int cnt=0,mark=0;
long long total=0;
len=strlen(str);
for(int i=0;i<len;i++)
{
if(str[i]=='(') cnt++;
if(str[i]==')'||str[i]=='?') cnt--;
if(str[i]=='?')
{
str[i]=')';
scanf("%d%d",&a,&b);
m.push(make(i,b-a));
total+=b;
}
if(cnt<0&&m.empty()) {mark=1;break;}
if(cnt<0)
{
cost tmp=m.top();
m.pop();
total=total-tmp.v;
str[tmp.id]='(';//这个位置之前误以为是str[i] 时刻记得 队列的顺序和遍历的顺序不是对应的！！！
cnt+=2;
}
}
if(cnt>0) mark=1;
if(mark) printf("-1\n");
else printf("%I64d\n%s\n",total,str);
//memset(str,0,sizeof(str));

return 0;
}


0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
碎碎念
周小姐，你还想毕业找不到工作吗？？？？
个人资料
• 访问：197408次
• 积分：7831
• 等级：
• 排名：第2657名
• 原创：599篇
• 转载：24篇
• 译文：0篇
• 评论：32条
友情链接