b659困難

逐層限幅的括號計算

保留原順序與運算符,求得到目標值的最少逐層限幅次數及最優樹形數。

效能範圍:來源未提供評測時限。WSL 本機n=45、B=15混合加減與隨機值實測:Python約4.14秒、C++17約0.23秒,兩者答案一致;大界案例並非獨立窮舉證明。嚴格時限建議C++17,不能保證Python通過未知時限。

解題思路

設 dp[l,r][v]=(最少限幅次數,方案數),葉只有輸入值、代價零、方案一。枚舉根切點 k 與左右可達值 x,y,以原第 k 個運算符計算 z,再夾到 [−B,B],額外代價是未夾值超出範圍的布林值。

固定切點與左右樹形唯一決定一棵樹,且每棵完整二元樹有唯一根切點,因此乘左右方案數、同代價相加不會重複。對相同區間值只保留最低代價,因為祖先只看值,較高代價永不可能改善答案。這也是不能只保留區間最小值或最大值的原因。

時間 O(n³(2B+1)²),空間 O(n²(2B+1));n≤45、B≤15,約一千五百萬對值合併上界。Python 輸入 O(n),稀疏字典只儲存可達值。

Step-by-step animation

逐步教學推演:依各步描述的例子觀察狀態、轉移與答案。

回報動畫錯誤
步驟 1 / 3

兩種根切點

數列 2,2,−2,B=2,皆為加號。

2
2
-2
樹形數
2

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll MOD = 1000000007;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n, B, T;
    cin >> n >> B >> T;
    vector<int> a(n);
    for (int &x : a)
        cin >> x;
    string op;
    if (n > 1)
        cin >> op;
    using P = pair<int, ll>;
    vector<vector<map<int, P>>> d(n, vector<map<int, P>>(n));
    for (int i = 0; i < n; i++)
        d[i][i][a[i]] = {0, 1};
    for (int len = 2; len <= n; len++)
        for (int l = 0; l + len <= n; l++) {
            int r = l + len - 1;
            for (int k = l; k < r; k++)
                for (auto [x, px] : d[l][k])
                    for (auto [y, py] : d[k + 1][r]) {
                        int z = op[k] == '+' ? x + y : x - y,
                            c = px.first + py.first + (abs(z) > B), v = clamp(z, -B, B);
                        ll w = px.second * py.second % MOD;
                        auto it = d[l][r].find(v);
                        if (it == d[l][r].end() || c < it->second.first)
                            d[l][r][v] = {c, w};
                        else if (c == it->second.first)
                            it->second.second = (it->second.second + w) % MOD;
                    }
        }
    if (!d[0][n - 1].count(T))
        cout << "-1 0\n";
    else {
        auto p = d[0][n - 1][T];
        cout << p.first << ' ' << p.second << '\n';
    }
}

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

更多