虽说是模板题,但一开始用自己的方法写,还是wa了好多次,由此可见自己对背包的认识还是不够
代码如下:
#include<iostream>
#include<algorithm>
#include<cstring>
#include<stack>
#include<queue>
#include<set>
#include<map>
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<time.h>
#include<math.h>
#define N 105
#define inf 0x7fffffff
#define eps 1e-9
#define pi acos(-1.0)
#define P system("pause")
using namespace std;
int n,v;
int cost[N],num[N];
int dp[100005];
void o1bag(int cost)
{
for(int i = v; i >= cost; i--)
dp[i] = max(dp[i], dp[i-cost]+cost);
}
void completebag(int cost)
{
for(int i = cost; i <= v; i++)
dp[i] = max(dp[i], dp[i-cost]+cost);
}
void multibag(int cost,int amount)
{
if(amount*cost >= v)
{
completebag(cost);
return ;
}
int i,k = 1;
while(k < amount)//这里有无等于号都可以
{
o1bag(k*cost);
amount -= k;
k *= 2;
}
o1bag(amount*cost);//注意这里是aamount,不是k
return ;
}
int main()
{
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
while(scanf("%d%d",&n,&v))
{
if(!n && !v) break;
int i;
for(i = 0 ; i < n; i++)
scanf("%d",&cost[i]);
for(i = 0; i < n; i++)
scanf("%d",&num[i]);
for(i = 1; i <= v; i++)
dp[i] = -inf;
dp[0] = 0;
for(i = 0; i < n; i++){
if(cost[i] > v) continue;
multibag(cost[i],num[i]);
}
int res = 0;
for(i = 1; i <= v; i++)
if(dp[i] > 0)
res++;
printf("%d\n",res);
}
return 0;
}