优先队列+括号配对 51Nod1476 括号序列的最小代价

传送门:点击打开链接

题意:这里有一个关于合法的括号序列的问题。
如果插入“+”和“1”到一个括号序列,我们能得到一个正确的数学表达式,我们就认为这个括号序列是合法的。例如,序列"(())()", "()"和"(()(()))"是合法的,但是")(", "(()"和"(()))("是不合法的。我们这有一种仅由“(”,“)”和“?”组成的括号序列,你必须将“?”替换成括号,从而得到一个合法的括号序列。
对于每个“?”,将它替换成“(”和“)”的代价已经给出,在所有可能的变化中,你需要选择最小的代价。

思路:刚开始把?全部用)替换。然后记录一下标记前缀和s,(标记为+1,)标记为-1。如果遇到某个时候s<0,那么就把之前的?里面里从右括号变成左括号需要的费用最少的改成(。并s+=2。这一步可以用优先队列来维护。

#include <map>
#include <set>
#include <cmath>
#include <ctime>
#include <stack>
#include <queue>
#include <cstdio>
#include <cctype>
#include <bitset>
#include <string>
#include <vector>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <functional>
#define fuck(x) cout<<"["<<x<<"]";
#define FIN freopen("input.txt","r",stdin);
#define FOUT freopen("output.txt","w+",stdout);
//#pragma comment(linker, "/STACK:102400000,102400000")
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
typedef long long LL;

const int MX = 5e4 + 5;

char S[MX];
int L[MX], R[MX];

int main() {
    //FIN;
    scanf("%s", S);
    int n = strlen(S);

    priority_queue<int> Q;
    LL sum = 0; bool ok = true;
    for(int i = 0; i < n; i++) {
        if(S[i] == '?') {
            scanf("%d%d", &L[i], &R[i]);
            sum += R[i];
        }
    }

    int now = 0;
    for(int i = 0; i < n; i++) {
        if(S[i] == '(') now++;
        else if(S[i] == ')' || S[i] == '?') now--;
        if(S[i] == '?') Q.push(R[i] - L[i]);
        if(now < 0) {
            if(Q.empty()) {
                ok = false; break;
            }
            sum -= Q.top(); Q.pop(); now += 2;
        }
    }
    if(now != 0) ok = false;
    printf("%I64d\n", ok ? sum : -1);
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值