问题描述
给定n个重量为{w1,w2,w3,…,wn}、价值为{v1,v2,v3,…,vn}的物品和一个容量为C的背包,0/1背包问题是求解这些物品中的一个最有价值的子集,并且要能够装到背包中。
代码
#include <iostream>
using namespace std;
int n; //表示物品的总数
int m; //表示背包承重
int ans = 0; //表示最优可行子集的物品数量
int r[50]; //r[]用来记录该子集的物品编号及价值
int temp_w = 0, temp_v= 0;
//定义一个结构体
struct goods //goods表示一个物品
{
int w; //w表示物品重量
int v; //v表示物品价值
bool flag; //flag表示是否选择该物品
}a[100];
// 记录当前子集,返回该子集物品数量
int get(int temp_v)
{
int i;
int count = 0;
r[0] = temp_v;
for (i = 0; i < n; ++i)
{
if (a[i].flag)
r[++count] = i + 1;
}
return count;
}
// 计算最优解
void fun(int x)
{
int i;
if (temp_w > m) //超重
return;
if (temp_v> r[0])//记录较优选择
ans = get(temp_v);
for (i = x; i < n; ++i)
{
// 加上第i件物品
temp_v = temp_v + a[i].v;
temp_w = temp_w + a[i].w;
a[i].flag = true;
// 递归处理下一个物品
fun(i + 1);
// 减去第i件物品
temp_v= temp_v - a[i].v;
temp_w = temp_w - a[i].w;
a[i].flag = false;
}
}
int main() {// 输入
int i;
cout << "输入物品个数和背包限制重量:" << endl;
cin >> n >> m;
for (i = 0;i < n;i++)
{
cout << "依次输入第" << i + 1 << "个物品的重量和价值" << endl;
cin >> a[i].w >> a[i].v;
}
fun(0);
cout << "最大总价值:";
cout << r[0] << endl;
return 0;
}