Hduoj1712【分组背包】

/*ACboy needs your help 
Time Limit : 1000/1000ms (Java/Other)   Memory Limit : 32768/32768K (Java/Other)
Total Submission(s) : 0   Accepted Submission(s) : 0
Font: Times New Roman | Verdana | Georgia 
Font Size: ← →
Problem 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

Source
HDU 2007-Spring Programming Contest */
#include<stdio.h>
#include<string.h>
int p1[110],p2[110][110], n, m;
int max(int x, int y)
{
	return x>y?x:y;
} 
int main()
{
	int i, j, k;
	while(scanf("%d%d", &n, &m) != EOF && (n || m))
	{
		for(i = 1; i <= n; ++i)
		{
			for(j = 1; j <= m; ++j)
			{
				scanf("%d", &p2[i][j]);//花j天能获得的价值
			}
		}
		memset(p1, 0, sizeof(p1));
		for(i = 1; i <= n; ++i)//n个课程 以课程为分组 
		for(j = m; j >= 1; --j)//容量逆序 
		{
			for(k = 1; k <= j; ++k)//消耗的容量所对应的课程 
			p1[j] = max(p1[j], p1[j-k] + p2[i][k]);
		}
		printf("%d\n", p1[m]); 
	}
	return 0;
}


题意:对于一个n*m的矩阵,AC需要用m天来上n门课,矩阵元素a【i,j】表示花费j天上第i门课可以获得的一个值,现在求给出m天能获得的最大值。

思路:这是一个比较明显的背包题,关键是多出了一维,直接将这一维放在逆序求最大值得外围即可。

你可能感兴趣的:(Hduoj1712【分组背包】)