程序填空题:Knapsack
You have $N$ items and a knapsack with a capacity of $W$. The weight of the $$i$$-th item is $w_i$ and the value is $v_i$. Suppose the number of each item is infinite, calculate the maximum sum of value if the total weight of the items does not exceed the capacity of the knapsack. All numbers are in the range of $[1, 1000]$.
c++
#include<bits/stdc++.h>
using namespace std;
int f[1010],w[1010],v[1010],n,W;
int main()
{
scanf("%d%d",&n,&W);
for(int i=1;i<=n;i++)
scanf("%d%d",&w[i],&v[i]);
for(int i=1;i<=n;i++)
for(int j=w[i];j<=W;j++)
printf("%d\n",);
return 0;
}
答案:
第1空:f[j]=max(f[j],f[j-w[i]]+v[i]);
第2空:f[W]
c++
#include<bits/stdc++.h>
using namespace std;
int f[1010],w[1010],v[1010],n,W;
int main()
{
scanf("%d%d",&n,&W);
for(int i=1;i<=n;i++)
scanf("%d%d",&w[i],&v[i]);
for(int i=1;i<=n;i++)
for(int j=w[i];j<=W;j++)
printf("%d\n",);
return 0;
}
答案:
第1空:f[j]=max(f[j],f[j-w[i]]+v[i]);
第2空:f[W]