题目表述:
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?
输入:
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.
输出:
For each data set, your program should output a line which contains the number of the max profit ACboy will gain.
样例输入:
2 2 1 2 1 3 2 2 2 1 2 1 2 3 3 2 1 3 2 1 0 0
样例输出:
3 4 6
关于分组背包的内容, 可以借阅背包九讲的内容。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
int main()
{
int n,m,a[110][110],f[110];
while(cin>>n>>m && n&&m)
{
memset(f,0,sizeof(f));
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++)//一共n门课程,从1到n
{
for(int j=m;j>=1;j--)//用的天数
{
for(int k=1;k<=j;k++)//输入第i门课的k,表示学第i门课用了k天的时间(自己这么理解的),可以将这个过程顺一遍,容易理解一些。k<=j是因为第一次的时候j是m,最后肯定确定了f[m],下一个for循环就不用再确定f[m]的值了,而下一个for循环j就是m-1,所以<=j是对的
f[j]=max(f[j],f[j-k]+a[i][k]);
}
}
cout << f[m]<<endl;
}
return 0;
}