a794困難有限付款與無限找零的雙動態規劃

CPE:Making Change (UVa 166)

枚舉實際付額,最小化付出與找回的硬幣總數。

前往題目練習 →回報教學錯誤B=p+39≤138、W=40B≤5520、cᵢ′=min(cᵢ,B);DP 時間 O(WΣlog(cᵢ′+1)+6W),工作空間 O(W)。另以 O(I) 時間讀取輸入字元;C++ 保存當筆數量字串,Python 另有整份輸入緩衝 O(I)。

解題思路

把金額統一除以 5 分,面額變為 1、2、4、10、20、40,價格 p<100。p=0 時不必交換硬幣,答案為 0。p>0 時,任意逐枚取錢包硬幣直到首次達到 p;因每枚至少 1 單位,至多付 p 枚,且最後一枚至多 40 單位,故溢付至多 39。店家用 1 單位硬幣找零至多 39 枚,因此必存在總交換數不超過 B=p+39≤138 的解。

最優解的付出枚數不超過總交換數,因此至多 B 枚,付額至多 W=40B≤5520。各面額只需保留 min(原數量,B) 枚;先移除數量字串可選的前導正號,再逐字讀數量並飽和到 B,之後才做任何數量乘法,不將巨大數量轉成固定長度整數,也不計算整個錢包總值。這個裁切仍保留至少一個最優解。

pay[s] 表示有限硬幣付出 s 的最少枚數,pay[0]=0,只計算到 W。將裁切後數量二進位分組,對每組做由大到小的 0/1 背包轉移,確保不超用;一組 g 枚的重量為 gv、成本為 g。店家的 change[s] 則以各面額無限、由小到大的轉移求最少找零枚數。

對每個可達且 p≤s≤W 的付額,取 pay[s]+change[s−p] 的最小值。價格以字串轉成整數分,小數不足兩位時在右側補零,例如 0.5 是 50 分;不使用浮點數。六個數量字串全為 0 時立即結束,不再讀價格;答案靠右寬度 3。

Step-by-step animation

示意:有一枚 1 元、售價 0.95 元

回報動畫錯誤
步驟 1 / 3

縮放單位

1 元變 20 單位,價格變 19 單位。

20
19
錢包枚數
1

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <iomanip>
using namespace std;
int main() {
    int v[] = {1, 2, 4, 10, 20, 40};
    string raw[6];
    while (cin >> raw[0]) {
        for (int i = 1; i < 6; ++i)
            cin >> raw[i];
        for (string &s : raw)
            if (!s.empty() && s[0] == '+')
                s.erase(0, 1);
        bool empty = true;
        for (const string &s : raw)
            if (s.find_first_not_of('0') != string::npos)
                empty = false;
        if (empty)
            break;
        string price;
        cin >> price;
        size_t pos = price.find('.');
        string whole = price.substr(0, pos);
        if (whole.empty()) whole = "0";
        string fraction = pos == string::npos ? "" : price.substr(pos + 1);
        fraction += "00";
        int p = (stoi(whole) * 100 +
                 10 * (fraction[0] - '0') + fraction[1] - '0') / 5;
        if (p == 0) {
            cout << setw(3) << 0 << '\n';
            continue;
        }
        int bound = p + 39, w = 40 * bound, c[6] = {};
        for (int i = 0; i < 6; ++i)
            for (char digit : raw[i])
                c[i] = min(bound, 10 * c[i] + digit - '0');
        const int inf = 100000000;
        vector<int> pay(w + 1, inf), change(w + 1, inf);
        pay[0] = change[0] = 0;
        for (int i = 0; i < 6; ++i) {
            int left = c[i];
            for (int group = 1; left; group *= 2) {
                int g = min(group, left);
                left -= g;
                for (int s = w; s >= g * v[i]; --s)
                    pay[s] = min(pay[s], pay[s - g * v[i]] + g);
            }
            for (int s = v[i]; s <= w; ++s)
                change[s] = min(change[s], change[s - v[i]] + 1);
        }
        int ans = inf;
        for (int s = p; s <= w; ++s)
            ans = min(ans, pay[s] + change[s - p]);
        cout << setw(3) << ans << '\n';
    }
}

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

更多