Least Cost Bracket Sequence(貪心)

Lourisy發表於2020-05-18

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則只可能是’(‘比‘)’多。(‘)’比‘(’多的在上面已經判過了)。

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\n");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\n");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\n");
	else printf("%lld\n%s",ans,s);
	return 0;
}

hzoi

相關文章