[贪心] 51Nod1476 括号序列的最小代价

要看清问题的本质。
实际上就是每个位置有两个权值,规定有多少个取的是第1个权值,剩下取第2个权值,求权值和最小值。
还需要满足括号序列合法,即把(看作 1 ) 看作 1,所有前缀和都非负。
假如不管括号序列,就直接先把所有的都取第一种权值,然后按差值排序,贪心的取。
而括号序列只是限制了序列的每个前缀至少需要几个是(
依然贪心就好了。先把待定的位置都设为)。从左到右扫,若当前前缀和小于 0 ,就在前面选最优的 1 变成 1 <script type="math/tex" id="MathJax-Element-314">1</script>,使其非负。

#include<queue>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long LL;
const int maxn=50005;
char st[maxn];
int n,len,m,a[maxn],b[maxn];
LL ans;
priority_queue<int,vector<int>,greater<int> > Heap; 
int main(){
    freopen("51Nod1476.in","r",stdin);
    freopen("51Nod1476.out","w",stdout);
    scanf("%s",st+1); len=strlen(st+1);
    int now=0;
    for(int i=1;i<=len;i++){
        if(st[i]=='?'){
            m++; scanf("%d%d",&a[m],&b[m]); ans+=b[m]; now--;
            Heap.push(a[m]-b[m]);
        } else
        if(st[i]=='(') now++; else now--;
        if(!Heap.empty()&&now<0) ans+=Heap.top(), Heap.pop(), now+=2;   
        if(now<0) return printf("-1"),0;
    }
    if(now>0) return printf("-1"),0;
    printf("%lld\n",ans);
    return 0;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值