模板多重背包

/**
*  多重背包:
*          有N种物品和一个容量为V的背包。第i种物品最多有Mi件可用,
*          每件耗费的空间是Ci,价值是Wi。
*          求解将哪些物品装入背包可使这些物品的耗费的空间总和不超过背包容量,且价值总和最大。
*/
#include <stdio.h>
#include <string.h>
int max(int a, int b){
	if (a > b)return a;
	return b;
}
#define maxn 100005
int c[maxn], w[maxn], num[maxn];//c:费用 w:价值 num:数量
int dp[maxn];           
int V;               //V:容量 V1:容量2

//01背包
void ZeroOnePack(int c, int w)
{
	for (int v = V; v >= c; v--)
	{
		dp[v] = max(dp[v], dp[v - c] + w);
	}
}
//完全背包
void CompletePack(int c, int w)
{
	for (int v = c; v <= V; v++)
	{
		dp[v] = max(dp[v], dp[v - c] + w);
	}
}
//多重背包
void MultiplePack(int c, int w, int num)
{
	if (c * num >= V)
	{
		CompletePack(c, w);
	}
	else
	{
		int k = 1;
		while (k < num)
		{
			ZeroOnePack(k*c, k*w);
			num -= k;
			k <<= 1;
		}
		ZeroOnePack(num*c, num*w);
	}
}
int main()
{
	int t;
	scanf("%d", &t);
	while (t--)
	{
		int n;
		scanf("%d%d", &V, &n);
		for (int i = 1; i <= n; i++)
			scanf("%d%d%d", &c[i], &w[i], &num[i]);
		memset(dp, 0, sizeof(dp));
		for (int i = 1; i <= n; i++)
			MultiplePack(c[i], w[i], num[i]);
		printf("%d\n", dp[V]);
	}
	return 0;
}
/*
1
10 5
5 1 1
4 2 1
3 3 1
2 4 1
1 5 1
**
14
*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值