代码:
#include
using namespace std;
int sum_v;//货物总价值
int sum_w;//货物总重量
int goodNum;//一共有多少货物
int ans;//背包中现有几个货物
int maxWeight;//背包的总容量
int r[100];//记录最后的选择的货物标号
using namespace std;
struct good
{
int weight;
int value;
int flag;//记录该货物是否被挑选
}goods[100];
//更新序列,并返回最大
int record(int sum_v)
{
int count_good = 0;
r[0] = sum_v;
for(int i = 1;i <= goodNum;i++)
{
if(goods[i].flag == 1)
{
r[++count_good] = i;
}
}
return count_good;
}
void findMin(int x)
{
if(sum_w > maxWeight)
{
return;
}
//最好在此处判断sun_v是否为最大,这样才不会有sum_w > maxWeight的情况
if(sum_v > r[0])
{
ans = record(sum_v);
}
//注意此处循环的条件
for(int i = x;i < goodNum;i++)
{
sum_w += goods[i].weight;
sum_v += goods[i].value;
goods[i].flag = 1;
findMin(i + 1);
sum_w -= goods[i].weight;
sum_v -= goods[i].value;
goods[i].flag = 0;
}
}
int main()
{
cout<<"请输入物件的个数和背包容量:";
cin >> goodNum >> maxWeight;
for(int i = 1;i <= goodNum;i++)
{
goods[i].flag = 0;
cout<<"第"< cin >> goods[i].weight >> goods[i].value;
}
findMin(0);
cout<<"背包内的物品组合为:";
for(int i = 1;i <= ans;i++)
{
cout << r[i] << " ";
}
cout<
return 0;
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)