b765困難

異型巢狀的加權括號修復

利用第一對括號的唯一配對位置,求最小替換費及結果字串數。

解題思路

函式 F(l,r,h,parent) 處理某父括號內的整片括號森林,h 為還能使用的深度,parent 是父型別或頂層無父。第一字元必為左括號,枚舉它的配對位置 k 與型別 t;若有父則 t 必與 parent 不同。內部用 F(l+1,k-1,h-1,t),右側並列部分用 F(k+1,r,h,parent)。

端點原字元與目標相同費用0,否則加該位置 c。各切分費用加總、方案數相乘,再在最小費用平手時相加。合法字串第一括號的配對位置及型別唯一,故分解不重複計數;零費替換也只按最終字元記一次。空區間 (0,1),奇數長或 h=0 的非空區間無解。

Python 雜湊記憶化期望時間 O(N³H),C++ 有序 map 版 O(N³H log(N²H+1));兩者空間 O(N²H),含記憶化與 O(N) 輸入。N,H≤32,精確結果數≤Catalan(16)·2^16<2^45,費用≤3.2·10^10,64位元足夠。

Step-by-step animation

逐步推演(例子條件見步驟說明)

回報動畫錯誤
步驟 1 / 3

原串與費用

自訂 S=(())、H=2,每位替換費1。

(
(
)
)
原始費用
0

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
    int n, H;
    string s;
    cin >> n >> H >> s;
    vector<ll> c(n);
    for (ll &x : c)
        cin >> x;
    const ll INF = LLONG_MAX / 4;
    map<tuple<int, int, int, int>, pair<ll, ll>> memo;
    function<pair<ll, ll>(int, int, int, int)> go = [&](int l, int r, int h,
                                                        int p) -> pair<ll, ll> {
        if (l > r)
            return {0, 1};
        if (!h || (r - l + 1) % 2)
            return {INF, 0};
        auto key = make_tuple(l, r, h, p);
        if (memo.count(key))
            return memo[key];
        pair<ll, ll> best = {INF, 0};
        for (int k = l + 1; k <= r; k += 2)
            for (int t = 0; t < 2; t++)
                if (t != p) {
                    auto [a, x] = go(l + 1, k - 1, h - 1, t);
                    auto [b, y] = go(k + 1, r, h, p);
                    if (a == INF || b == INF)
                        continue;
                    char op = t ? '[' : '(', cl = t ? ']' : ')';
                    ll v = a + b + (s[l] == op ? 0 : c[l]) + (s[k] == cl ? 0 : c[k]);
                    if (v < best.first)
                        best = {v, x * y};
                    else if (v == best.first)
                        best.second += x * y;
                }
        return memo[key] = best;
    };
    auto [v, w] = go(0, n - 1, H, 2);
    if (v == INF)
        cout << "-1 0\n";
    else
        cout << v << ' ' << w << '\n';
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多