題意:用m天的時間來學n門課程,給出n和m和一個num[n][m]的矩陣,num[n][m] 代表的是花m天的時間學習第n門課程所獲得的價值,求最多能獲得多大的價值
思路:將天數m作為背包的總體積,科目數目作為背包的種類數目,天數j作為背包的重量,num[i][j]作為背包的價值。由於一個科目只能選一次,即滿足一組背包只能選一個,即轉化為多組背包問題。www.2cto.com
代碼:
[cpp]
#include <iostream>
#include <string.h>
#include <cstdio>
using namespace std;
#define CLR(arr,val) memset(arr,val,sizeof(arr))
const int N = 110;
int num[N][N],dp[N];
struct course{
int val,weight;
}cc[110];
int main(){
//freopen("1.txt","r",stdin);
int numkind,totalweight;
while(scanf("%d%d",&numkind,&totalweight) &&numkind&&totalweight){
CLR(num,0);
int x;
for(int i = 1;i <= numkind;++i){
for(int j = 1;j <= totalweight;++j){
scanf("%d",&num[i][j]);
}
}
CLR(dp,0);
for(int i = 1;i <= numkind;++i){
for(int w = totalweight;w > 0;--w){
for(int j = 0;j <= totalweight;++j){
if(w >= j)
dp[w] = max(dp[w],dp[w - j] + num[i][j]);
}
}
}
int mmax = 0;
for(int i = 0;i <= totalweight;++i)
if(mmax < dp[i])
mmax = dp[i];
printf("%d\n",mmax);
}
return 0;
}
作者:wmn_wmn