首页 > 其他 > 详细

51nod 1476 括号序列的最小代价 (括号题套路+反悔贪心)

时间:2018-09-05 23:18:07      阅读:362      评论:0      收藏:0      [点我收藏+]

题意:给一串只有‘(‘ , ‘)‘ , ‘?‘ 的括号序列,每个?可以变成)或者(,代价分别为bi和ai,求变成合法序列的最小代价

思路:学习自最近的网络赛&&51nod贪心专题视频的思想,“反悔”,一般在获取收益有限制的情况下使用

先按某种“优”的策略贪心,如果不满足限制条件了,取一个修改后代价尽可能小的状态修改成满足条件的状态,得到新的满足限制下的最优解

这种贪心常常可以借助优先队列实现

然后是括号题的套路:把(当做1,把)当做-1,做前缀和

这题中,先当做所有的?都换成右括号,这是显然的,顺推只要前缀和小于0就是不合法,需要“反悔”,优先队列维护ai和bi的差值,每次取换成左括号最便宜的问号转换

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<algorithm>
 4 #include<iostream>
 5 #include<queue>
 6 #define LL long long
 7 #define debug(x) cout << "[" << x << "]" << endl
 8 using namespace std;
 9 
10 const int mx = 50010;
11 char s[mx];
12 LL a[mx], b[mx];
13 
14 int main(){
15     priority_queue<LL> q;
16     int sum = 0;
17     LL ans = 0;
18     scanf("%s", s);
19     int len = strlen(s);
20     for (int i = 0; i < len; i++)
21         if (s[i] == ?) scanf("%lld%lld", &a[i], &b[i]);
22     for (int i = 0; i < len; i++){
23         if (s[i] == () sum++;
24         else {
25             sum--;
26             if (s[i] == ?) {
27                 ans += b[i];
28                 q.push(b[i]-a[i]);
29             }
30         }
31         if (sum < 0){
32             if (q.empty()){
33                 printf("-1\n");
34                 return 0;
35             }
36             ans -= q.top();
37             sum += 2;
38             q.pop();
39         }
40     }
41     if (sum != 0) printf("-1\n");
42     else printf("%lld\n", ans);
43     return 0;
44 }

 

51nod 1476 括号序列的最小代价 (括号题套路+反悔贪心)

原文:https://www.cnblogs.com/QAQorz/p/9595184.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!