Least Cost Bracket Sequence
题目描述
给你一个括号序列,里面有?,?可以是左括号或右括号,但你要保证最后括号序列合法,而且?变成左右括号的代价不同,你需要保证最后代价最小
解题思路
首先判断一个括号序列合不合法,可以用一个值w来判断,左括号+1,右括号-1,然后先把所有的问号当作右括号,并存储每个问号的左右代价差值,从小到大排列,当w小于0时,把队列中头部变成左括号
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
typedef pair<int,int> P;
const int N=5*1e4+5;
char s[N];
int main()
{
scanf("%s",s);
int len = strlen(s);
int w=0,a,b;
long long ans = 0;
priority_queue<P,vector<P>, greater<P> > q;
for(int i=0;i<len;i++){
if(s[i] == '(') w++;
else if(s[i] == ')') w--;
else{
w--;
scanf("%d %d",&a,&b);
ans += b;
q.push(make_pair(a-b,i));
s[i] = ')';
}
if(w < 0){
if(q.empty()){
cout << -1 << endl;
return 0;
}
else{
ans += q.top().first;
s[q.top().second] = '(';
q.pop();
w += 2 ; //少一个右括号,多一个左括号
}
}
}
if(w){
cout << -1 << endl;
return 0;
}
else{
cout << ans << endl;
cout << s << endl;
}
return 0;
}