分组背包问题+求具体方案
$ 时间复杂度O(NMM),空间复杂度O(NM) $
需要用一维数组来记录每组选的什么
参考文献
算法提高课
AC代码
#include <iostream>
using namespace std;
const int N = 30;
int n, m;
int g[N][N],f[N][N];
int way[N];
int main(){
//读入
cin >> n >> m;
for (int i = 1 ; i <= n ; i ++)
for (int j = 1 ; j <= m ; j ++)
cin >> g[i][j];
//分组背包
for (int i = 1 ; i <= n ; i ++){
for (int j = 0 ; j <= m ; j ++){
f[i][j] = f[i - 1][j];
for (int k = 1 ; k <= m ; k ++){
if (j >= k )f[i][j] = max(f[i][j], f[i - 1][j - k] + g[i][k]);
}
}
}
cout << f[n][m] << endl;
//求方案
int j = m;
for (int i = n ; i >= 1 ; i --){
for (int k = 0 ; k <= m ; k ++){
if (j >= k && f[i][j] == f[i - 1][j - k] + g[i][k]){
way[i] = k;
j -= k;
break;
}
}
}
for (int i = 1 ; i <= n ; i ++) cout << i << " " << way[i] << endl;;
return 0;
}