描述:
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.
代码:
多重背包问题,不要求装满背包。
#include<stdio.h> #include<string.h> #include<iostream> #include<stdlib.h> #include <math.h> using namespace std; #define MAX 105 int main(){ int n,m,dp[MAX][MAX],value[MAX][MAX],max; while( scanf("%d%d",&n,&m)!=EOF && n!=0 && m!=0 ){ memset(value,0,sizeof(value)); for( int i=1;i<=n;i++ ) for( int j=1;j<=m;j++ ) scanf("%d",&value[i][j]); memset(dp,0,sizeof(dp));//并未要求背包放满 for( int i=1;i<=n;i++ ){ for( int j=1;j<=m;j++ ){ max=0; for( int k=0;k<=j;k++ )//第i个物品放0-j个 max=(max>dp[i-1][j-k]+value[i][k])?max:dp[i-1][j-k]+value[i][k]; dp[i][j]=max;//背包容量为j,放前i个物品得到的最大值 } } printf("%d ",dp[n][m]); } system("pause"); return 0; }
空间复杂度优化。可以看出,当计算dp[i][j]时,用到的数值为dp[i-1][0]到dp[i-1][j]的值,故背包容量的遍历顺序需反序,可以将dp二维数组优化为一维。
#include<stdio.h> #include<string.h> #include<iostream> #include<stdlib.h> #include <math.h> using namespace std; #define MAX 105 int main(){ int n,m,dp[MAX],value[MAX][MAX],max; while( scanf("%d%d",&n,&m)!=EOF && n!=0 && m!=0 ){ memset(value,0,sizeof(value)); for( int i=1;i<=n;i++ ) for( int j=1;j<=m;j++ ) scanf("%d",&value[i][j]); memset(dp,0,sizeof(dp));//并未要求背包放满 for( int i=1;i<=n;i++ ){ for( int j=m;j>=1;j-- ){ max=0; for( int k=0;k<=j;k++ )//第i个物品放0-j个 max=(max>dp[j-k]+value[i][k])?max:dp[j-k]+value[i][k]; dp[j]=max;//背包容量为j,放前i个物品得到的最大值 } } printf("%d ",dp[m]); } system("pause"); return 0; }