CF3D

http://blog.csdn.net/black_miracle/article/details/69307458


Least Cost Bracket Sequence
time limit per test
 1 second
memory limit per test
 64 megabytes
input
 standard input
output
 standard output

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.

Examples
input
(??)
1 2
2 8
output
4
()()


题意:给你一串序列  每个问号变成 ( 的代价和变成 ) 的代价  问最小匹配代价和匹配后的序列是什么


题解:我们可以假设?全部是右括号  那么for过去  如果发现一个点  左括号个数小于右括号  那么我们可以从前面的问号拿出一个转化代价最小的  转化为左括号

这么做下去 判掉不可能的情况即可


#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
typedef long long ll;
struct node{
    int num,lab;
    bool operator<(const node& a)const{
        return num>a.num;
    }
}e[50005];
char s[50005];
priority_queue<node,vector<node>,less<node> >sp;
int main(){
    int n,i,j;
    scanf("%s",s+1);
    int len=strlen(s+1);
    ll ans=0;
    int l=0,r=0,flag=1,x,y;
    for(i=1;i<=len;i++){
        if(s[i]=='(')l++;
        else if(s[i]==')')r++;
        else{
            scanf("%d%d",&x,&y);
            ans+=y;
            sp.push((node){x-y,i});
            r++;
        }
        if(l<r){
            if(sp.empty())flag=0;
            else{
                ans+=sp.top().num;
                s[sp.top().lab]='(';
                sp.pop();
                r--;
                l++;
            }
        }
    }
    if(!flag||l!=r)printf("-1\n");
    else{
        printf("%lld\n",ans);
        for(i=1;i<=len;i++)printf("%c",s[i]=='?'?')':s[i]);
        printf("\n");
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值