Coins
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 12318 Accepted Submission(s): 4917
Problem Description
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.
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 0 0
Sample Output
8 4
此题的多重背包,采用的是二进制拆分优化,可作模板。
二进制拆分优化主要参考博客: http://blog.youkuaiyun.com/insistgogo/article/details/11176693
对每i件物品,拆分的策略为:新拆分的物品的重量等于1件,2件,4件,..,(2^(k - 1)),Num[i] - (2^(k - 1))件,其中k 是满足Num[i] - 2^k + 1 > 0 的最大整数。
并且还有一个优化的小细节:
(1)如果第i个物品的重量Weight[i] * 物品的个数Num[i] >= 背包总重量V,可以不用拆分,转化为完全背包。
(2)如果第i个物品的重量Weight[i] * 物品的个数Num[i] < 背包总重量V,需要拆分,转化为01背包。
对于计数问题,用
num=0;
for(i=1;i<=m;i++)
{
if(dp[i]>0)
num++;
}
printf("%d\n",num);
即可。
AC代码:
#include <stdio.h>
#include <string.h>
#define max(a,b) a>b?a:b
int main()
{
int m,n,i,j,k,n1,num,a[1005],c[1005],dp[100005];
while(scanf("%d %d",&n,&m)!=EOF)
{
if(m==0&&n==0)
break;
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
for(i=1;i<=n;i++)
scanf("%d",&c[i]);
for(i=1;i<=m;i++)
dp[i]=-10000000;
for(i=1;i<=n;i++)
{
if(a[i]*c[i]>=m)
{
for(j=a[i];j<=m;j++)
dp[j]=max(dp[j],dp[j-a[i]]+a[i]);
}
else
{
k=1;
n1=c[i];
while(k<=n1)
{
for(j=m;j>=k*a[i];j--)
dp[j]=max(dp[j],dp[j-k*a[i]]+k*a[i]);
n1-=k;
k*=2;
}
for(j=m;j>=n1*a[i];j--)
dp[j]=max(dp[j],dp[j-n1*a[i]]+n1*a[i]);
}
}
num=0;
for(i=1;i<=m;i++)
{
if(dp[i]>0)
num++;
}
printf("%d\n",num);
}
return 0;
}