Problem
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.
题意:告诉你硬币有几种,每种的面额和数量,还有商品的上限价格,求该价格有几种可能
用多重背包会t,可以每次遍历时判一下,分成完全背包和二进制优化来做
ac代码如下
#include<iostream>
#include<algorithm>
#include<string.h>
typedef long long ll;
using namespace std;
ll dp[100005];
ll val[105];
ll num[105];
int main()
{
ll n, m;
while(cin >> n >> m)
{
if (n == 0 && m == 0)
break;
memset(dp, 0, sizeof(dp));
memset(val, 0, sizeof(val));
memset(num, 0, sizeof(num));
for (int i = 1; i <= n; i++)
cin >> val[i];
for (int i = 1; i <= n; i++)
cin>>num[i];
for (int i = 1; i <= n; i++)
{
if (val[i] * num[i] >= m) //当做完全背包来处理
for (int j = val[i]; j <= m; j++)
{
dp[j] = max(dp[j], dp[j - val[i]] + val[i]);
}
else//<=时当做01背包处理,并用二进制优化
{
ll sum = num[i];
for (int k = 1; k < sum; k = k * 2)
{
for (int j = m; j >= k * val[i]; j--)
dp[j] = max(dp[j], dp[j - k * val[i]] + k * val[i]);
sum -= k;
}
if (sum>0)
for (int j = m; j >= sum * val[i]; j--)
dp[j] = max(dp[j], dp[j - sum * val[i]] + sum * val[i]);
}
}
ll ans = 0;
for (int i = 1; i <= m; i++)
if (dp[i] == i) //找到满足的条件
ans++;
cout << ans << endl;
}
return 0;
}
本文深入探讨了多重背包问题,一种常见的计算机科学与算法竞赛题目。文章详细解释了如何使用完全背包和二进制优化的01背包方法解决该问题,通过实例代码展示了具体的实现过程,旨在帮助读者理解和掌握多重背包问题的解决技巧。
434

被折叠的 条评论
为什么被折叠?



