题目 :
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.
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
多组背包 :每组中的物品至多选一个
二维代码 :( 用原来的那个数组直接更新 )

1 #include<iostream> 2 3 using namespace std; 4 5 int main( ){ 6 7 int n,m,dp[105][105]={0},Max; 8 while(1) { 9 10 cin >>n >>m; 11 if( n==0 && m==0 ) break; 12 for( int i=1;i<=n;i++) 13 for( int j=1;j<=m;j++) 14 cin >>dp[i][j]; 15 16 for( int i=2;i<=n;i++) { 17 for( int j=m;j>=1;j--){ 18 Max=dp[i][j]; 19 // 对 第i行第j行 位置更新 20 // 因为dp[i-1][j-k] 是 第i-1行第j-k行 位置 的最优解 ,所以对于 一个dp[i][k] 应该对应的 + dp[i-1][j-k],得一个较大值。 21 for( int k=1;k<j;k++) 22 Max=max( Max, dp[i-1][j-k]+dp[i][k] ); 23 dp[i][j]=max( Max, dp[i-1][j] ) ; 24 } 25 } 26 Max=-1; 27 28 for( int i=1;i<=m;i++) 29 Max=max( Max, dp[n][i] ); 30 cout <<Max <<endl; 31 } 32 }
一维数组 :

1 #include<iostream> 2 #include<cstring> 3 4 using namespace std; 5 6 int main( ){ 7 8 int n,m,V[105][105]={0},dp[105]; 9 while(1) { 10 11 cin >>n >>m; 12 if( n==0 && m==0 ) break; 13 memset (dp,0,sizeof(dp)); 14 15 for( int i=1;i<=n;i++) 16 for( int j=1;j<=m;j++) 17 cin >>V[i][j]; 18 19 for( int i=1;i<=n;i++) 20 for( int j=m;j>=1;j--) 21 for( int k=0;k<=j;k++) 22 dp[j]=max( dp[j], dp[j-k]+V[i][k] ); 23 for( int i=1;i<=m;i++) 24 dp[0]=max( dp[0],dp[i] ); 25 26 cout <<dp[0] <<endl; 27 } 28 }