您的位置:首页 > 其它

HDU 1712 ACboy needs your help (简单分组背包)

2016-08-02 11:29 495 查看

ACboy needs your help

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 6242    Accepted Submission(s): 3427


[align=left]Problem Description[/align]

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?

 

[align=left]Input[/align]

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.

 

[align=left]Output[/align]

For each data set, your program should output a line which contains the number of the max profit ACboy will gain.

 

[align=left]Sample Input[/align]

2 2
1 2
1 3
2 2
2 1
2 1
2 3
3 2 1
3 2 1
0 0

 

[align=left]Sample Output[/align]

3
4
6

题意: 有N门课,花费M天。不同课程的收益取决于在它上花费的时间。怎样为N门课程安排M天让总收益最大化?

解题思路:就是一道分组背包模板题。

以下是背包九讲的内容:
6 分组的背包问题
6.1 问题
有N件物品和一个容量为V 的背包。第i件物品的费用是Ci,价值是Wi。这 些物品被划分为K组,每组中的物品互相冲突,最多选一件。求解将哪些物品 装入背包可使这些物
品的费用总和不超过背包容量,且价值总和最大。

6.2 算法
这个问题变成了每组物品有若干种策略:是选择本组的某一件,还是一件 都不选。也就是说设F[k,v]表示前k组物品花费费用v能取得的最大权值,则 有:
 F[k,v] = max{F[k−1,v],F[k−1,v−Ci] + Wi |item i ∈ group k} 使用一维数组的伪代码如下:
for k = 1 to K for v = V to 0 for item i in group k F[v] = max{F[v],F[v−Ci] + Wi} 这里三层循环的顺序保证了每一组内的物品最多只有一个会被添
加到背包中。 另外,显然可以对每组内的物品应用2.3中的优化。

6.3 小结
分组的背包问题将彼此互斥的若干物品称为一个组,这建立了一个很好的 模型。不少背包问题的变形都可以转化为分组的背包问题(例如7),由分组的 背包问题进一步可
定义“泛化物品”的概念,十分有利于解题。

<span style="font-size:18px;">#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
const int maxn=105;
int value[maxn][maxn];
int dp[maxn];
int main()
{
int n,m;
while(~scanf("%d %d",&n,&m) && (n||m))
{
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++){
scanf("%d",&value[i][j]);
}
}
memset(dp,0,sizeof(dp));
for(int i=1;i<=n;i++)
{
for(int j=m;j>=0;j--)
{
for(int k=1;k<=j;k++)
{
if(dp[j]<dp[j-k]+value[i][k])
dp[j]=dp[j-k]+value[i][k];
}
}
}
printf("%d\n",dp[m]);
}
return 0;
}</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  背包