a677困難找零與守恆金額壓縮狀態

CPE:Buying Coke (UVa 10626)

記住剩餘瓶數、5 元與 10 元硬幣,推回 1 元硬幣數。

前往題目練習 →回報教學錯誤設實際到達狀態數為 S,每狀態五個轉移,時間與空間 O(S);狀態界 O(C(n5+n10+1)(n10+1))。

解題思路

購買過程的總金額每瓶恰減 8。若還要買 r 瓶、持有 f 枚 5 元與 t 枚 10 元,則 1 元數可由初始總金額 V 推回:one=V−8(C−r)−5f−10t。以 (r,f,t) 作記憶化狀態,避免多記一維;r=0 時後續成本為 0。

只需考慮五種不被支配的付款:8 個 1 元;1 個 5 元加 3 個 1 元;2 個 5 元找 2 個 1 元;1 個 10 元找 2 個 1 元;1 個 10 元加 3 個 1 元找 1 個 5 元。最後一種雖多投硬幣,可能為未來保留 5 元,不能省略。其他多付方式可去掉多餘硬幣,或調整到後續購買而不增加總投入。對持幣足夠的轉移,加付款枚數取最小。

Step-by-step animation

示意:C=2,持有 2 個1元、1個5元、1個10元

回報動畫錯誤
步驟 1 / 3

初始

總金額 17,可支付兩瓶的 16。

1元:2
5元:1
10元:1
r
2
投入
0

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <unordered_map>
#include <functional>
#include <algorithm>
using namespace std;
int main() {
    int tests;
    cin >> tests;
    while (tests--) {
        int c, n1, n5, n10;
        cin >> c >> n1 >> n5 >> n10;
        int value = n1 + 5 * n5 + 10 * n10;
        unordered_map<long long, int> memo;
        function<int(int, int, int)> solve = [&](int r, int f, int t) {
            if (r == 0)
                return 0;
            long long key = (1LL * r * 256 + f) * 64 + t;
            if (memo.count(key))
                return memo[key];
            int one = value - 8 * (c - r) - 5 * f - 10 * t, answer = 1000000;
            if (one >= 8)
                answer = min(answer, 8 + solve(r - 1, f, t));
            if (f >= 1 && one >= 3)
                answer = min(answer, 4 + solve(r - 1, f - 1, t));
            if (f >= 2)
                answer = min(answer, 2 + solve(r - 1, f - 2, t));
            if (t >= 1)
                answer = min(answer, 1 + solve(r - 1, f, t - 1));
            if (t >= 1 && one >= 3)
                answer = min(answer, 4 + solve(r - 1, f + 1, t - 1));
            return memo[key] = answer;
        };
        cout << solve(c, n5, n10) << '\n';
    }
}

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

更多