CodeForces - 3D Least Cost Bracket Sequence【贪心】

【题目描述】
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.

【输入】
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.

【输出】
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.

【样例输入】
(??)
1 2
2 8

【样例输出】
4
()()

题目链接:https://codeforces.com/contest/3/problem/D

很有意思的一道贪心题,
先把每个问号看作右括号,优先队列维护修改代价,当左括号数量小于右括号时,修改代价最小的。

代码如下:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
struct Node{
    int cost,pos;
    friend bool operator<(Node p,Node q)
    {
        return p.cost>q.cost;
    }
};
int main()
{
    std::ios::sync_with_stdio(false);
    std::cin.tie(0),cout.tie(0);
    string s;
    cin>>s;
    int a,b;
    int pre=0;
    ll ans=0;
    priority_queue<Node> Q;
    for(int i=0;i<s.size();i++)
    {
        if(s[i]=='(') pre++;
        else if(s[i]==')') pre--;
        else
        {
            cin>>a>>b;
            s[i]=')';
            ans+=b;
            Q.push(Node{a-b,i});
            pre--;
        }
        if(pre<0)
        {
            if(Q.empty())
            {
                cout<<-1<<endl;
                return 0;
            }
            pre+=2;
            ans+=Q.top().cost;
            s[Q.top().pos]='(';
            Q.pop();
        }
        
    }
    if(pre!=0)
        cout<<-1<<endl;
    else
    {    
        cout<<ans<<endl;
        cout<<s<<endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值