多重背包,是一个将背包装满的问题,所以在设初始值时,要将其设为无穷小即可,这里我是用我自己的想法,初始值仍然是0,这里可以理解装满的问题,我设初始值为0那么加了那些值之后,只要是能用那些硬币表示出来的数就一定会出现在f[]数组值里,而m表示这些硬币要凑出的数,所以f[m]如果等于m的话那么它就能凑出m这个数,否则就必不会等于,因为这里我们是将它的体积和价值视为一样的,即都是硬币的面值。这里理解清楚了,就差不多了。只要在设判断是是f[m] == m?就可以不用管初始值时0还是负无穷,随便设一个都可以。
下面贴上代码:218 MS
#include <stdio.h>
#include <string.h>
int f[100005];
int a[100005];
int num[1005];
void ZeroOnePack(int cost,int weight,int V){
int v;
for(v = V; v >= cost; --v){
if(f[v] < f[v - cost] + weight)
f[v] =f[v - cost] + weight;
}
}
void CompletePack(int cost,int weight,int V){
int v;
for(v = cost; v <= V; v++){
if(f[v] < f[v - cost] + weight)
f[v] =f[v - cost] + weight;
}
}
void MultiplePack(int cost,int weight,int amount,int V){
if(cost * amount >= V){
CompletePack(cost,weight,V);return ;
}
int k = 1;
while(k < amount){
ZeroOnePack(k * cost,k * weight,V);
amount -= k;
k *=2;
}
ZeroOnePack(amount * cost,amount * weight,V);
}
int main()
{
int n,m,k,i,re;
while(scanf("%d%d",&n,&m)){
if(!n&&!m)break;
memset(f,0,sizeof(f));
for(i = 1; i <= n; i++){
scanf("%d",&a[i]);
}
for(i = 1; i <= n; i++){
scanf("%d",&num[i]);
if(num[i] > 1)
MultiplePack(a[i],a[i],num[i],m);
else ZeroOnePack(a[i],a[i],m);
}
k = 0;
for(i = 1; i <= m; i++){
if(f[i] == i) {
k++;
}
}
printf("%d\n",k);
}
return 0;
}