问题描述
In a strange shop there are n types of coins of value A1,A2,…,An. C1,C2,…,Cn denote the number of coins of value A1,A2,…,An respectively. You have to find the number of different values (from 1 to m), which can be produced using these coins.
输入格式
Input starts with an integer T (T≤10), denoting the number of test cases.
Each case starts with a line containing two integers n (1≤n≤100) and m (1≤K≤100 000). The next line contains 2n integers, denoting A1,A2,…,An,C1,C2,…,Cn (1≤Ai≤100 000,1≤Ci≤1 000). All Ai will be distinct.
输出格式
For each case, print the case number and the result.
样例
input
2 3 10 1 2 4 2 1 1 2 5 1 4 2 1output
Case 1: 8 Case 2: 4
思路:一开始用基本的部分背包解法会超时 ,看了解答发现还是需要技巧的。。。状态方程dp[j+A[i]] = max(dp[j+A[i]], dp[j]-1),其中dp[j]在每一轮循环中表示当前币种i在凑到金额j时还可以使用的数量,初始值为C[i],即最大可用量。每次更新时保证剩余可用的硬币数最多,这样可以尽量多的凑出不同的金额,代码如下:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
int T;
cin>>T;
for(int cas=1; cas<=T; ++cas){
int n, m, cnt=0;
int A[101], C[101];
int *dp = (int*)malloc(100001*sizeof(int));
memset(dp, -1, 100001*sizeof(int));
dp[0] = 0;
cin>>n>>m;
for(int i=0; i<n; ++i)
cin>>A[i];
for(int i=0; i<n; ++i)
cin>>C[i];
for(int i=0; i<n; ++i){//考虑每个币种
for(int j=0; j<=m; ++j)//初始化
if(dp[j]>=0)//若当前金额可以由前i-1种硬币凑到
dp[j] = C[i];//则在该金额的基础上还可以叠加C[i]个币种i
for(int j=0; j+A[i]<=m; ++j)//再次循环,开始分配币种个数
if(dp[j]>0)//如果当前金额还可以叠加的币种i个数大于0,则考虑是叠加还是不叠加
dp[j+A[i]] = max(dp[j+A[i]], dp[j]-1);//选择叠加后剩余可用硬币数量多的情况,因为这样可以凑出更多种金额
}
for(int i=1; i<=m; ++i)
if(dp[i]>=0)//统计可得金额
++cnt;
printf("Case %d: %d\n", cas, cnt);
}
return 0;
}