codeforces 3D - Least Cost Bracket Sequence(贪心)

题目大意给你一串不确定的括号以及'?',其中'?'可以替换成为‘(’与‘)’,并且不同的‘(’需要支付一定的价格,在保证括号合法性的情况下保证最少的价格



分析:

有两个要点:合法性与最少的价格

所以可以在最少价格情况下修正合法性,也可以在保证合法性的情况下修正最小的价格

首先,计算合法性的要点:对于一个括号串,'('即+1,')'即-1,然后把所有的'?'都变成')',如果数值变成负数,则从前面找一个可以使当前括号串价格最小的一个位置变成'(',用优先队列处理。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
#define MAX_NUM            50007
typedef long long LL;
char set[MAX_NUM];
LL fir[MAX_NUM];
LL las[MAX_NUM];
struct node{
    LL number;
    LL stp;
    friend bool operator< (node n1, node n2)  
    {
        return n1.number < n2.number;
    } 
    node(LL a,LL b):number(a),stp(b){}
};

priority_queue<node> que;
int main(int argc, char const *argv[])
{
    gets(set+1);
    int strl = strlen(set+1);
    int cnt = 0;
    for (int i = 1; i <= strl ; ++i)
    {
        if(set[i] == '?')
            cnt++;
    }
    for (int i = 1; i <= cnt; ++i)
    {
        scanf("%lld%lld",&fir[i],&las[i]);
    }
    int col = 1;
    cnt = 0;
    LL ans = 0;
    for (int i = 1; i <= strl ; ++i)
    {
        if(set[i] == '(')
            cnt++; 
        else if(set[i] == ')')
            cnt--;
        else{
            cnt--;
            set[i] = ')';
            ans += las[col];
            que.push(node(las[col] - fir[col],i));
            col++;
        }
        if(cnt < 0)
        {
            if(que.empty()){
                printf("-1\n");
                return 0;
            }
            node tem = que.top();
            que.pop();
            ans-=tem.number;
            set[tem.stp] = '(';
            cnt +=2;
        }
    }
    if(cnt==0)
        printf("%lld\n%s\n",ans,set+1);
    else
        printf("-1\n");
    return 0;
}

 

posted @ 2017-05-18 09:10  miamiao  阅读(244)  评论(0编辑  收藏  举报