b372中等

CSES 1634|最少硬幣(Minimizing Coins)

以動態規劃逐步構成目標金額或點數。

解題思路

以動態規劃逐步構成目標金額或點數。

先枚舉金額s,再枚舉最後一枚硬幣c,dp[s]=min(dp[s−c]+1)。最後一枚涵蓋全部可能性,金額遞增時所有較小來源已經定案。

不可達狀態初值為x+1,最後仍大於x就輸出−1。

時間 O(nx),空間 O(x+n),含輸入硬幣。

Step-by-step animation

無限硬幣的最少枚數逐步追蹤

回報動畫錯誤
步驟 1 / 3

步驟 1

目標12,面額1、4、7。

dp0=0
步驟
1

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
    int n, x;
    cin >> n >> x;
    vector<int> c(n);
    for (int &v : c)
        cin >> v;
    sort(c.begin(), c.end());
    vector<int> d(x + 1, x + 1);
    d[0] = 0;
    for (int s = 1; s <= x; s++)
        for (int v : c) {
            if (v > s)
                break;
            d[s] = min(d[s], d[s - v] + 1);
        }
    cout << (d[x] > x ? -1 : d[x]) << '\n';
}

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

更多