Least Cost Bracket Sequence

· · 个人记录

Least Cost Bracket Sequence

思路

考虑 dp,设 dp_{ij} 表示前 i 个位置有 j 个闲的,然后保证转移时 j 始终大于等于 0,最终保证 j = 0 即可获得暴力做法。

如果对于一个即将不满足的右括号,找到更改量最小的,然后更改。由于前面的可以保证都是匹配的,所以不管改哪个都是正确的,所以改更改量最小的,如果没有,就是无解,最后看是否匹配即可。 ## code ```cpp #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; } ```