資源簡介
01背包問題回溯法
代碼片段和文件信息
#include?“iostream“
#include?“stdio.h“
#define?maxGoodsNum?20
using?namespace?std;
int?num?maxValue?currentValue?currentWeight?bagWeight;//物品數(shù)量,最大價值,當(dāng)前價值,當(dāng)前重量,背包容量
int?currentGoods[maxGoodsNum]?=?{?0?};//背包物品,
struct?goods?{
int?weight;//物品重量
int?value;//物品價值
int?number;//物體序號,按輸入次序排列;從goods[1]開始存放
}goods[maxGoodsNum];
//交換函數(shù)
void?swap(int&?a?int&?b)?{
int?temp;
temp?=?a;
a?=?b;
b?=?temp;
};
void?swap(struct?goods&?good1?struct?goods&?good2)?{
swap(good1.value?good2.value);
swap(good1.weight?good2.weight);
swap(good1.number?good2.number);
}
//排序函數(shù),按單位價值排序
void?sort()?{
int?perValue[maxGoodsNum];
for?(int?i?=?1;?i?<=?num;?i++)?{
perValue[i]?=?goods[i].value?/?goods[i].weight;
}
for?(int?i?=?1;?i?<=?num?-?1;?i++)?{
for?(int?j
評論
共有 條評論