动态规划背包问题——分组背包

本文深入探讨了分组背包问题,一种特殊的背包问题变种,其中物品被划分成多个组,每组只能选择一个物品。文章通过实例讲解了状态转移方程及伪代码实现,并附带AC代码,适合初学者理解并掌握分组背包算法。

分组背包

问题背景:
有一个容量为V的背包,有N件物品。每一件物品的体积为c[i],价值为v[i],这些物品被划分为若干组,每组中的物品最多选一件,因为他们互相冲突,求出最佳方案,使背包中的总价值最大。
这个问题变成了这一组的物品你选一件或者一件都不选。
状态转移方程为

f[j][k] = max(f[j – c[i]][k – 1] + v[i], f[j][k – 1])物品i属于k组

可以写出伪代码:

for 所有的组k
	for j=V...c[i]
	for 所有的i属于组k
	f[j] = max(f[j], f[j - c[i]] + v[i]) 

这里要特别注意是这几层循环的顺序,第二层循环必须在第三层循环之外,这样才能保证每一组中最多只有一个可以被添加到背包中。
最后以一道杭电oj的分组背包入门题来介绍:
问题描述:
ACboy has N courses this term, and he plans to spend at most M days on study.Of course,the profit he will gain from different course depending on the days he spend on it.How to arrange the M days for the N courses to maximize the profit?
Input:
The input consists of multiple data sets. A data set starts with a line containing two positive integers N and M, N is the number of courses, M is the days ACboy has.
Next follow a matrix A[i][j], (1<=i<=N<=100,1<=j<=M<=100).A[i][j] indicates if ACboy spend j days on ith course he will get profit of value A[i][j].
N = 0 and M = 0 ends the input.
Output
For each data set, your program should output a line which contains the number of the max profit ACboy will gain.
样例:
Input:
2 2
1 2
1 3
2 2
2 1
2 1
2 3
3 2 1
3 2 1
0 0
Output:
3
4
6
分析:这个懒孩子有N门课要上,但是他只想学习M天(我们不要学他,认真上课)
然后会输入上j天课可以得到A[i][j]的价值,(i就是不同的课程,也就是组)为什么要是分组背包呢,因为一门课你不可能上一天又上两天对吧。分析到这不就简单了吗?
贴上AC代码:

#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int f[10010], A[101][101];
int main()
{
	int n,m;
	while(cin >> n >> m)
	{
		memset(f,0,sizeof(f));
		if(!n&&!m)
		break;
		for(int i = 1; i <= n; i++)
		for(int j = 1; j <= m; j++)
		cin >> A[i][j];
		for(int i = 1; i <= n; i++)
		for(int j = m; j >= 1; j--)
		for(int k = 1; k <= j; k++)
		f[j] = max(f[j], f[j - k] + A[i][k]);
		cout << f[m] << endl;
	}
	return 0;
 } 

注:此文章问原创,开源,可转载但请注明出处!

说明:这一讲参考了《背包九讲》,也在这里感谢《背包九讲》作者给我入门背包问题。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值