当前位置: 代码迷 >> 综合 >> Optimal Coin Change(完全背包 路径记录)
  详细解决方案

Optimal Coin Change(完全背包 路径记录)

热度:81   发布时间:2023-12-05 21:35:40.0

路径记录记一手。

#include <bits/stdc++.h>
int v, n, f[17], dp[10007], pre[10007], inf = 0x3f3f3f3f, ans[10007];
int main() {
//    freopen("in.txt", "r", stdin);while (~scanf("%d%d", &v, &n)) {memset(dp, 0x3f, sizeof(dp));memset(ans, 0, sizeof(ans));for (int i = 1; i <= n; i++) scanf("%d", f + i);dp[0] = 0;for (int i = 1; i <= n; i++) {for (int j = f[i]; j <= v; j++) {if (dp[j - f[i]] < inf && dp[j - f[i]] + 1 <= dp[j]) {dp[j] = dp[j - f[i]] + 1;pre[j] = j - f[i];}}}if (dp[v] == inf) puts("-1");else {int cur = v;while (cur) {ans[cur - pre[cur]]++;cur = pre[cur];}for (int i = 1; i <= n; i++) printf("%d%c", ans[f[i]], i == n ? '\n' : ' ');}}return 0;
}

  相关解决方案