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 gainfrom different course depending on the days he spend on it.How to arrange the Mdays for the N courses to maximize the profit?
Input
The input consists of multipledata sets. A data set starts with a line containing two positive integers N andM, 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 spendj 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, yourprogram should output a line which contains the number of the max profit ACboywill 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门课,你有m天时间。一天只能上一门。一门课上一天的利益可能比上两天还多,但可能比三天少。也就是说,每门课只能得到上的天数的相应利益,而不是累加利益。问最大利益是多少。
思路:分组背包问题。
1 //分组背包 2 #include<cstdio> 3 #include<cstring> 4 #include<algorithm> 5 using namespace std; 6 int map[105][105];//i课程花j天的利润 7 int dp[105];//花x天时的利润 8 int n,m; 9 10 int main(){ 11 while(scanf("%d%d",&n,&m)){ 12 if(n==0&m==0) break; 13 memset(map,0,sizeof(map)); 14 memset(dp,0,sizeof(dp)); 15 16 for(int i=1;i<=n;i++){ 17 for(int j=1;j<=m;j++){ 18 scanf("%d",&map[i][j]); 19 } 20 } 21 22 for(int i=1;i<=n;i++){ 23 for(int j=m;j>=1;j--){//j是容量,每找一个课程更新一下最大利润 24 for(int k=1;k<=j;k++){//k是所耗天数, 25 dp[j]=max(dp[j],dp[j-k]+map[i][k]);//j-k耗k天之前的利润 26 } 27 } 28 } 29 printf("%d ",dp[m]); 30 } 31 return 0; 32 }