HDU-1712-ACboy needs your help
Description
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.
Sample Input
2 2
1 2
1 3
2 2
2 1
2 1
2 3
3 2 1
3 2 1
0 0
Sample Output
3
4
6
题意
- 多组输入,每组以N和V开头,当N和V均为0时程序结束
- N代表有N门课,V代表有V天
- 接下来是N*V的矩阵,第i行第j个数,代表花费 j 天学习 i 这门课所得的收获
- 每组数据输出花费这V天,所得的最多收获
题解
- 这是分组背包的模板题,对模板进行微改即可
- 此题中,每门课只能选择一个天数进行学习,所以一门课一组,组内成员为天数
- 三层循环,头组数,尾组员,中间夹着的是容量,dp[]括号内的也是容量,此题容量为天数
- 把每一门课归为一组,最后当做一个01背包中的物品
- 天数遍历的时候是1到 j 不会超出容量
- 注意 01背包一维数组空间优化后,所谓的内层循环逆序,是 容量逆序,即为此题的第二层逆序
涉及知识点
- 背包 算法(此题属于分组背包)
- 对于背包的算法-详见链接博客介绍背包
AC代码
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int maxn=1e3+10;
int T,n,v,Value[maxn][maxn],value[maxn],value1[maxn],cost[maxn],cost1[maxn],dp[maxn];
int knapsack_divide()//分组背包
{
memset(dp,0,sizeof(dp));
for(int i=1;i<=n;i++)//第i组,即每门课1组
{
for(int j=v;j>=1;j--)//背包容量j,即容量是天数
{
for(int k=1;k<=j;k++)//这组中第k个,选几天
{
dp[j]=max(dp[j],dp[j-k]+Value[i][k]);
}
}
}
return dp[v];
}
int main()
{
while(~scanf("%d %d",&n,&v)&&n+v)
{
memset(Value,0,sizeof(Value));
for(int i=1;i<=n;++i)
{
for(int j=1;j<=v;++j)
{
scanf("%d",&Value[i][j]);
}
}
printf("%d\n",knapsack_divide());
}
return 0;
}