题目连接点击打开链接
简单的多重背包问题,代码如下:
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#define INF 110
using namespace std;
int dp[INF];
void CompletePack(int cost,int weight,int n)
{
for(int i=cost;i<=n;i++)
dp[i]=max(dp[i],dp[i-cost]+weight);
}
void Zero_OnePack(int cost,int weight,int n)
{
for(int i=n;i>=cost;i--)
dp[i]=max(dp[i],dp[i-cost]+weight);
}
int main()
{
int cost[INF],weight[INF],amount[INF],ncase;
cin>>ncase;
while(ncase--)
{
int m,n;
memset(dp,0,sizeof(dp));
scanf("%d%d",&n,&m);
for(int i=0;i<m;i++)
scanf("%d%d%d",&cost[i],&weight[i],&amount[i]);
for(int i=0;i<m;i++)
{
if(cost[i]*amount[i]>n)
CompletePack(cost[i],weight[i],n);
else
{
int k=1;
while(k<amount[i])
{
Zero_OnePack(cost[i]*k,weight[i]*k,n);
amount[i]-=k;
k*=2;
}
Zero_OnePack(cost[i]*amount[i],weight[i]*amount[i],n);
}
}
printf("%d\n",dp[n]);
}
}