用背包问题来介绍贪心算法:
背包问题:有一个背包,背包容量是M=150。有7个物品,物品可以分割成任意大小。要求尽可能让装入背包中的物品总价值最大,但不能超过总容量。
物品 A B C D E F G
重量 35 30 60 50 40 10 25
价值 10 40 30 50 35 40 30
$weight = [35, 30, 60, 50, 40, 15, 20];
$value = [10, 40, 30, 50, 35, 40, 30];
$total_weight = 150;
bag($weight, $value, $total_weight);
function bag($weight, $value, $total_weight)
{
$product = [];
foreach ($weight as $k => $v) {
$product[] = ['weight' => $v, 'value' => $value[$k], 'pj_value' => ($value[$k] / $v)];
}
$total_value = 0;
$sorted_product = sortByPj_value($product);
print_r($sorted_product);
$total = 0;
foreach ($sorted_product as $k => $v) {
if ($total + $v['weight'] <= $total_weight) {
$total_value += $v['value'];
$total += $v['weight'];
} elseif ($total < $total_weight) {
for ($j = $k + 1; $j < count($sorted_product); $j++) {
if (($sorted_product[$j]['weight'] + $total) <= 150) {
$total_value += $sorted_product[$j]['value'];
$total += $sorted_product[$j]['weight'];
}
}
break;
}else{
break;
}
}
echo $total . PHP_EOL;
echo $total_value . PHP_EOL;
}
function sortByPj_value($product)
{
for ($i = 0; $i < count($product); $i++) {
for ($j = $i + 1; $j < count($product); $j++) {
if ($product[$i]['pj_value'] < $product[$j]['pj_value']) {
$temp = $product[$i];
$product[$i] = $product[$j];
$product[$j] = $temp;
}
}
}
return $product;
}