这题不太容易想到……
其实还是很简单的
先把所有的?换成’)’,然后一路扫过去
如果不符合配对的要求就在之前的?中找修正代价最小的
用优先队列维护一下,然后就好了
示例程序:
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
typedef long long ll;
const int maxn=50005;
int n,m,a[maxn],b[maxn];
ll ans;
char s[maxn];
priority_queue<int,vector<int>,greater<int> > Q;
int main(){
scanf("%s",s);n=strlen(s);
for (int i=0;i<n;i++) if (s[i]=='?') m++;
for (int i=1;i<=m;i++) scanf("%d%d",&a[i],&b[i]);
int S=0;
for (int i=0,t=0;i<n;i++){
if (s[i]=='?'){
t++;ans+=b[t];Q.push(a[t]-b[t]);S--;
}else S+=(s[i]=='(')?1:-1;
while (!Q.empty()&&S<0) S+=2,ans+=Q.top(),Q.pop();
if (S<0) return printf("-1"),0;
}
if (S>0) return printf("-1"),0;
printf("%lld",ans);
return 0;
}

本文介绍了一种使用优先队列优化括号匹配问题的算法。通过将问号替换为右括号并遍历字符串,利用优先队列动态调整以达到最小化修正成本的目的。
3712

被折叠的 条评论
为什么被折叠?



