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

分组背包

问题背景:
有一个容量为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;
 } 

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

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

猜你喜欢

转载自blog.csdn.net/yezi_coder/article/details/103526013
今日推荐