Least Cost Bracket Sequence(贪心)
Describe
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 a i and b i (1 ≤ a i, b i ≤ 106), where a i is the cost of replacing the i-th character "?" with an opening bracket, and b i — 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.
Examples
Input
(??)
1 2
2 8
Output
4
()()
Solution
因为左右括号匹配,我们从第一个字符遍历,定义一个sum=0,‘(’ 就 +1 ,‘)’ 就-1,‘?’ 就做相应的处理(下面再说),我们要保证遍历过程中一直让sum>=0,当然可以使用‘?’,如果遍历到一个地方,即使使用'?'sum仍<0,输出-1.
为了让()完美匹配,他给的’(‘ 和 ‘)’ 就不能改了,所以我们要处理'?',从左向右遍历,如果遇到一个‘?’,将’?‘变为‘)’仍满足sum>=0,那么我们就让‘?’变为‘)’(因为我们一直让左括号不少的嘛),如果?变为)之后,sum<0了,我们就在前面(包括这一个)找一个贡献大的变为)的?,使之变为(。
最后判定sum,sum==0正确输出,sum!=0则只可能是’(‘比‘)’多,输出-1。(‘)’比‘(’多的在上面已经判过了)。
Code
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <queue>
#include <iostream>
using namespace std;
const int maxn=5e4+5;
typedef long long ll;
char s[maxn];
int sum;
ll ans;
priority_queue<pair<int,int> > q;
int main(){
scanf("%s",s);
int len=strlen(s),x,y;
for(int i=0;i<len;++i){
if(s[i]=='(')sum++;
else if(s[i]==')'){
sum--;
if(sum<0){
if(q.empty()){printf("-1
");return 0;}
else{
int xx=q.top().first,yy=q.top().second;q.pop();
ans-=(ll)xx;
s[yy]='(';
sum+=2;
}
}
}
else if(s[i]=='?'){
scanf("%d%d",&x,&y);
q.push(make_pair(y-x,i));//后面要改就先改y-x值大的,这样贡献才最大
s[i]=')';
ans+=(ll)y;
sum--;
if(sum<0){
if(q.empty()){printf("-1
");return 0;}
else{
int xx=q.top().first,yy=q.top().second;q.pop();
ans-=(ll)xx;
s[yy]='(';
sum+=2;
}
}
}
}
if(sum!=0)printf("-1
");
else printf("%lld
%s",ans,s);
return 0;
}
hzoi