Least Cost Bracket Sequence
思路
考虑 ,设 表示前 个位置有 个闲的,然后保证转移时 始终大于等于 ,最终保证 即可获得暴力做法。
不行,考虑贪心,由于对于每个位置有两个决策点,但是有一定的规则,所以虽然无法直接的有一个规则来贪心,但是可以通过反悔规则来达到最优,根据括号匹配规则,可知,如果都改左括号,那么直到最后才存在不匹配,显然不可取,所以将所有的改为右括号。
如果对于一个即将不满足的右括号,找到更改量最小的,然后更改。由于前面的可以保证都是匹配的,所以不管改哪个都是正确的,所以改更改量最小的,如果没有,就是无解,最后看是否匹配即可。
code
#include <iostream>
#include <queue>
using namespace std;
const int MaxN = 5e4 + 10;
struct S {
long long x, id;
bool operator<(const S &j) const {
return x > j.x;
}
};
long long a[MaxN], b[MaxN], ans, n;
char c[MaxN];
priority_queue<S> q;
bool GGG(int x, int &cnt) {
if (cnt == 0) {
if (q.empty()) {
return 1;
} else {
ans += q.top().x, c[q.top().id] = '(';
q.pop();
cnt++;
}
} else {
cnt--;
}
return 0;
}
bool Work() {
cin >> c + 1;
for (int i = 1; c[i] != 0; i++, n++) {
if (c[i] == '?') {
cin >> a[i] >> b[i];
}
}
int cnt = 0;
for (int i = 1; i <= n; i++) {
if (c[i] == '(') {
cnt++;
} else if (c[i] == ')') {
if (GGG(i, cnt)) {
return 1;
}
} else {
ans += b[i];
q.push({a[i] - b[i], i});
c[i] = ')';
if (GGG(i, cnt)) {
return 1;
}
}
}
return cnt;
}
int main() {
if (Work()) {
cout << -1 << endl;
} else {
cout << ans << endl;
for (int i = 1; i <= n; i++) {
cout << c[i];
}
}
return 0;
}