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

来源:互联网 发布:淘宝打包能学到什么 编辑:程序博客网 时间:2024/05/19 12:40

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

#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