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

Posted qaqorz

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了51nod 1476 括号序列的最小代价 (括号题套路+反悔贪心)相关的知识,希望对你有一定的参考价值。

题意:给一串只有‘(‘ , ‘)‘ , ‘?‘ 的括号序列,每个?可以变成)或者(,代价分别为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
");
34                 return 0;
35             }
36             ans -= q.top();
37             sum += 2;
38             q.pop();
39         }
40     }
41     if (sum != 0) printf("-1
");
42     else printf("%lld
", ans);
43     return 0;
44 }

 

以上是关于51nod 1476 括号序列的最小代价 (括号题套路+反悔贪心)的主要内容,如果未能解决你的问题,请参考以下文章

51Nod2594 括号之价

51nod 1791合法括号子段

Least Cost Bracket Sequence 思维

51nod1403 有趣的堆栈

Day2下午

0718题解-FOIWC实在是太美