ACboy needs your help(HDU 1712 分组背包入门)
ACboy needs your help
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 5872 Accepted Submission(s): 3196
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
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
分组背包,背包容量m,物品分为n组,每组只能取一件,求背包最大价值。
dp[i][j]表示对于前i组物品,背包容量为j时的最大价值,此时对于每种dp[i][j]需要遍历第i组的每一个物品,求出最大的dp[i][j];
状态转移方程:
dp[i][j]=max(dp[i][j],dp[i-1][j-k]+ma[i][k])
1 #include <iostream> 2 #include <cstring> 3 #include <cstdio> 4 #include <algorithm> 5 using namespace std; 6 #define Max 105 7 int dp[Max][Max],ma[Max][Max]; 8 int n,m; 9 int main() 10 { 11 int i,j; 12 memset(ma,0,sizeof(ma)); 13 freopen("in.txt","r",stdin); 14 while(scanf("%d%d",&n,&m)) 15 { 16 if(n==0&&m==0) 17 break; 18 for(i=1;i<=n;i++) 19 for(j=1;j<=m;j++) 20 scanf("%d",&ma[i][j]); 21 memset(dp,0,sizeof(dp)); 22 for(i=1;i<=n;i++) 23 { 24 for(j=1;j<=m;j++) 25 { 26 for(int k=0;k<=j;k++) 27 { 28 if(dp[i][j]<dp[i-1][j-k]+ma[i][k]) 29 dp[i][j]=dp[i-1][j-k]+ma[i][k]; 30 } 31 //cout<<dp[i][j]<<" "; 32 } 33 // cout<<endl; 34 } 35 printf("%d\n",dp[n][m]); 36 } 37 return 0; 38 }