鉴于很多背包模板写的自己觉得不太习惯,封装成了函数并且标注了使用方法
#include<bits/stdc++.h>
using namespace std;
int dp[1005];
int w[1005], v[1005];//w表示物品重量, v表示物品价值
int c[1005];// c表示多重背包每件物品的个数
int m,n; //m表示背包容量, n表示物品种类
void zeroonepack(int cost, int weight)
{
for(int v = m; v >= cost; --v)
dp[v] = max(dp[v], dp[v-cost]+weight);
}
void completepack(int cost, int weight)
{
for(int v = cost; v <= m; ++v)
dp[v] = max(dp[v], dp[v-cost]+weight);
}
void multipack(int cost, int weight, int num)
{
if(cost*num >= m)
{
completepack(cost, weight);
return;
}
int k = 1;
//二进制拆分多重背包
while(k < num)
{
zeroonepack(k*cost, k*weight);
num -= k;
k <<= 1;
}
zeroonepack(num*cost, num*weight);
}
int main()
{
ios::sync_with_stdio(false);
int T;
cin >> T;
while(T--)
{
cin >> m >> n;
/*初始化条件*/
memset(dp, 0, sizeof(dp)); //只要求价值最大,不必须装满背包
for(int i = 0; i < 1005; ++i) dp[i] = -0x3f3f3f3f; dp[0] = 0; //要求把背包恰好装满
/*数据输入*/
for(int i = 0; i < n; ++i)
cin >> w[i] >> v[i] >> c[i] ;
/*0-1背包*/
for(int i = 0; i < n; ++i)
zeroonepack(w[i], v[i]);
/*完全背包*/
for(int i = 0; i < n; ++i)
completepack(w[i], v[i]);
/*多重背包*/
for(int i = 0; i < n; ++i)
multipack(w[i], v[i], c[i]);
int result = dp[m];
}
}