贪心算法不能用来解决离散物品问题的原因是我们无法将“ 半台电视” 放入背包。 规则是按照物品价值高低顺序放入背包。
function ksack(values, weights, capacity) { var load = 0; var i = 0; var v = 0; while (load < capacity && i < weights.length) { if (weights[i] <= (capacity - load)) { v += values[i]; load += weights[i]; } else { var r = (capacity - load) / weights[i]; v += r * values[i]; load += weights[i]; } ++i; } return v; } var items = [ "A", "B", "C", "D" ]; var values = [ 50, 140, 60, 60 ]; var weights = [ 5, 20, 10, 12 ]; var capacity = 30; document.write(ksack(values, weights, capacity)); // 显示 220
时间: 2024-10-14 16:16:11