1、背包问题求具体方案(01求具体方案)
不能使用状态压缩的方式(将二维优化成一维),求的时候就是将每个状态反推一遍。
#include <iostream>
using namespace std;
const int N = 1010;
int n, m;
int v[N], w[N];
int f[N][N];
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i ++ ) cin >> v[i] >> w[i];
//从f[n][0]->f[1][m]枚举状态 使得f[1][m]为最大值
for (int i = n; i >= 1; i -- )
for (int j = 0; j <= m; j ++ )
{
f[i][j] = f[i + 1][j];
if (j >= v[i]) f[i][j] = max(f[i][j], f[i + 1][j - v[i]] + w[i]);
}
//从最大值f[1][m]找方案
int j = m;
for (int i = 1; i <= n; i ++ )
//判断 只能选以及 可选可不选的条件
if (j >= v[i] && f[i][j] == f[i + 1][j - v[i]] + w[i])
{
cout << i << ' ';
//选择
j -= v[i];
}
return 0;
}
2、机器分配(分组背包问题求具体方案)
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 11, M = 16;
int n, m;
int w[N][M];
int f[N][M];
//记录方案
int way[N];
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i ++ )
for (int j = 1; j <= m; j ++ )
cin >> w[i][j];
for (int i = 1; i <= n; i ++ )
for (int j = 0; j <= m; j ++ )
for (int k = 0; k <= j; k ++ )
//需要记录路径,则需要计算二维
f[i][j] = max(f[i][j], f[i - 1][j - k] + w[i][k]);
cout << f[n][m] << endl;
//从后向前推
int j = m;
//f[n][m]最大值 i是公司分组
for (int i = n; i; i -- )
//枚举第i个公司分配几个机器
for (int k = 0; k <= j; k ++ )
if (f[i][j] == f[i - 1][j - k] + w[i][k])
{
//i公司分配几个
way[i] = k;
j -= k;
break;
}
//公司编号 从小到大输出
for (int i = 1; i <= n; i ++ ) cout << i << ' ' << way[i] << endl;
return 0;
}
3、金明的预算方案(分组背包)
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#define v first
#define w second
using namespace std;
typedef pair<int, int> PII;
const int N = 60, M = 32010;
int n, m;
PII master[N];
vector<PII> servent[N];
int f[M];
int main()
{
cin >> m >> n;
for (int i = 1; i <= n; i ++ )
{
int v, p, q;
cin >> v >> p >> q;
p *= v;
//q为0表示当前物品是主件
if (!q) master[i] = {v, p};
//否则是附件
else servent[q].push_back({v, p});
}
//分组背包问题 个数
for (int i = 1; i <= n; i ++ )
//体积
for (int u = m; u >= 0; u -- )
{ //决策
for (int j = 0; j < 1 << servent[i].size(); j ++ )
{
int v = master[i].v, w = master[i].w;
for (int k = 0; k < servent[i].size(); k ++ )
if (j >> k & 1)
{
v += servent[i][k].v;
w += servent[i][k].w;
}
if (u >= v) f[u] = max(f[u], f[u - v] + w);
}
}
cout << f[m] << endl;
return 0;
}
4、开心的金明(01)
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 30010;
int n, m;
int f[N];
int main()
{
cin >> m >> n;
for (int i = 0; i < n; i ++ )
{
int v, w;
cin >> v >> w;
w *= v;
for (int j = m; j >= v; j -- )
f[j] = max(f[j], f[j - v] + w);
}
cout << f[m] << endl;
return 0;
}