a967困難

97 全國資訊學科能力競賽(2008)|5. 蛋糕師傅的煩惱

保留所有可能有用的寬高組合。

解題思路

每片蛋糕有兩個旋轉尺寸。依後序序列用堆疊計算,每遇 H 或 V 就取出兩個子樹的候選尺寸,兩兩組合套用題目公式。

同寬只需最小高度;若某尺寸的寬、高都不小於另一尺寸,它在任何上層 max 或加法合併都不會更好,故可刪掉。按寬遞增排序後,只保留高度嚴格下降的項目。

候選包含每種旋轉方案,刪除只移除被支配尺寸,單調的合併公式保證不會丟掉最佳解。最後對根候選取最小 w×h。

若每個節點候選至多 F,L片蛋糕,O(L F² log(F+1)) 時間、O(LF+F²) 空間;尺寸正整數且總邊長≤L×49,F≤L×49。 Python一次讀入另佔O(輸入文字長度)空間。

Step-by-step animation

示例:蛋糕1為2×2,蛋糕2可3×1或1×3。

回報動畫錯誤
步驟 1 / 3

兩片候選

蛋糕1為2×2,蛋糕2可3×1或1×3。

(2,2)
(3,1)
(1,3)
合併
H

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
using P = pair<int, int>;
vector<P> prune(vector<P> a) {
    sort(a.begin(), a.end());
    vector<P> b;
    int h = INT_MAX;
    for (auto x : a)
        if (x.second < h) {
            b.push_back(x);
            h = x.second;
        }
    return b;
}
int main() {
    string line;
    getline(cin, line);
    istringstream in(line);
    vector<string> tok;
    string s;
    while (in >> s)
        tok.push_back(s);
    map<int, vector<P>> leaf;
    int id, w, h;
    while (cin >> id >> w >> h)
        leaf[id] = prune({{w, h}, {h, w}});
    vector<vector<P>> st;
    for (string t : tok) {
        if (t != "H" && t != "V") {
            st.push_back(leaf[stoi(t)]);
            continue;
        }
        auto b = move(st.back());
        st.pop_back();
        auto a = move(st.back());
        st.pop_back();
        vector<P> z;
        for (auto [w1, h1] : a)
            for (auto [w2, h2] : b)
                z.push_back(t == "H" ? P{max(w1, w2), h1 + h2}
                                     : P{w1 + w2, max(h1, h2)});
        st.push_back(prune(z));
    }
    long long ans = LLONG_MAX;
    for (auto [w, h] : st.back())
        ans = min(ans, 1LL * w * h);
    cout << ans << '\n';
}

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

更多