贪心算法之背包问题

用背包问题来介绍贪心算法:
背包问题:有一个背包,背包容量是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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值