Board question: It’s just that this board is better than the one in the book; the
meaning of the question: select m from n fruits, and only one can be selected at a time, so that the sum of a is the largest, so this is a 01 knapsack problem; Change the form
and then regard 0 as the backpack capacity, ai-k*bi as the weight, and ai as the value;
so it is a 01 backpack, but due to negative numbers, the backpack capacity needs to be expanded;
specific code:
#include<bits/stdc++.h>
using namespace std;
const int C=2e5+100;
int n,k,w[110],v[110];
int a[110];
int dp[200][C];
int INF=0x3f3f3f3f;
int main(){
scanf("%d %d",&n,&k);
for(int i=0;i<n;i++)
{
scanf("%d",&v[i]);//价值
a[i]=v[i];
}
memset(dp,-INF,sizeof(dp));//如果必须装满,那么就初始化为-1,如果在容量不超过W的情况下那么就初始化为0
dp[0][C/2]=0;
for(int i=0;i<n;i++)scanf("%d",&w[i]);//重量
for(int i=0;i<n;i++)w[i]=v[i]-k*w[i];
for(int i=0;i<n;i++){
for(int j=0;j<C;j++){
dp[i+1][j]=dp[i][j];
if(j>=w[i]&&j<w[i]+C){
dp[i+1][j]=max(dp[i+1][j],dp[i][j-w[i]]+a[i]);
}
}
}
if(dp[n][C/2]<=0)puts("-1");
else printf("%d\n",dp[n][C/2]);
return 0;
}