K - Coins(多重背包的变种题)

这是一个关于如何用C语言解决多重背包问题的实例。给定不同面值的硬币和数量,以及最大价格m,目标是计算可以使用这些硬币支付多少种不同的价格。通过标记硬币能表示的价值并利用二进制优化,可以找出能用硬币表示的m以内所有价值中被标记过的数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

Whuacmers use coins.They have coins of value A1,A2,A3…An Silverland dollar. One day Hibix opened purse and found there were some coins. He decided to buy a very nice watch in a nearby shop. He wanted to pay the exact price(without change) and he known the price would not more than m.But he didn’t know the exact price of the watch.
You are to write a program which reads n,m,A1,A2,A3…An and C1,C2,C3…Cn corresponding to the number of Tony’s coins of value A1,A2,A3…An then calculate how many prices(form 1 to m) Tony can pay use these coins.
Input
The input contains several test cases. The first line of each test case contains two integers n(1 ≤ n ≤ 100),m(m ≤ 100000).The second line contains 2n integers, denoting A1,A2,A3…An,C1,C2,C3…Cn (1 ≤ Ai ≤ 100000,1 ≤ Ci ≤ 1000). The last test case is followed by two zeros.
Output
For each test case output the answer on a single line.
Sample Input
3 10
1 2 4 2 1 1
2 5
1 4 2 1

#include <iostream> #include <vector> #include <climits> using namespace std; const int INF = 0x3f3f3f3f; // 表示无穷大 struct Node { int prev; // 前一个金额状态 int idx; // 硬币类型索引 int cnt; // 使用该硬币的数量 }; int main() { int amt, n; // amt: 目标金额, n: 硬币种类数 cout << "输入总金额: "; cin >> amt; cout << "输入硬币种类数: "; cin >> n; vector<int> val(n), lim(n); // val: 硬币面值, lim: 每种硬币的数量限制 for (int i = 0; i < n; i++) { cout << "输入第" << i+1 << "种硬币的面值和数量: "; cin >> val[i] >> lim[i]; } // dp[i]表示凑出金额i所需的最少硬币数 vector<int> dp(amt + 1, INF); // path记录状态转移路径 vector<Node> path(amt + 1, {-1, -1, -1}); dp[0] = 0; // 初始状态:凑出0元需要0个硬币 // 动态规划处理每种硬币 for (int i = 0; i < n; i++) { // 多重背包解法:对每种硬币的数量进行遍历 for (int j = amt; j >= val[i]; j--) { // 尝试使用1到lim[i]个当前硬币 for (int k = 1; k <= lim[i] && k * val[i] <= j; k++) { if (dp[j - k * val[i]] != INF && dp[j] > dp[j - k * val[i]] + k) { dp[j] = dp[j - k * val[i]] + k; path[j] = {j - k * val[i], i, k}; // 记录路径 } } } } // 输出结果 if (dp[amt] == INF) { cout << "无法凑出目标金额" << endl; return -1; } cout << "\n最少硬币数: " << dp[amt] << endl; // 回溯构造方案 vector<int> used(n, 0); // 记录每种硬币使用数量 int curr = amt; while (curr > 0) { int prev = path[curr].prev; int idx = path[curr].idx; int cnt = path[curr].cnt; used[idx] += cnt; // 累加硬币使用量 curr = prev; } cout << "硬币使用方案:\n"; for (int i = 0; i < n; i++) { if (used[i] > 0) { cout << " 面值 " << val[i] << " 的硬币: " << used[i] << " 个\n"; } } return 0; }
06-14
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值