CF3D Least Cost Bracket Sequence TJ
阿新 • • 發佈:2020-10-26
思路
貪心法,先將所有的 \(?\) 設定為 \()\) ,然後進行括號匹配,如果不匹配,則查詢前面最優的 \()\) 換成 \((\) ,對此我們可以用一個堆來維護。
程式碼
#include <cstdio> #include <cstring> #include <queue> #include <algorithm> using namespace std; const int MAXN = 5e4 + 10; struct node { int val; int ind; bool operator < (const node &x) const { return val > x.val; } }a[MAXN]; priority_queue <node > p; char s[MAXN]; int n = 0 ,lens ,sum = 0; long long ans = 0; int main () { scanf ("%s",s); lens = strlen (s); for (int q = 0;q < lens;++ q) { if (ans == -1) break; if (s[q] == '?') { sum --; int l ,r; scanf ("%d%d",&l ,&r); a[++ n].ind = q ,a[n].val = l - r; p.push(a[n]); s[q] = ')'; ans += r; } else if (s[q] == '(') { sum ++; } else { sum --; } if (sum < 0) { if (p.empty()) { ans = -1; } if (ans != -1) { sum += 2; node x = p.top(); p.pop(); s[x.ind] = '('; ans += x.val; } } } if (sum != 0) ans = -1; printf ("%I64d\n",ans); if (ans != -1) { printf ("%s\n",s); } return 0; }