PHP入门到精通教程
首页 > PHP入门到精通教程 > 背包装入最大价值总和

背包装入最大价值总和

2020-09-10 11:03:58 34

编辑 收藏

$list = [
    [
        'id' => 'a',
        'weight' => 2,
        'money' => 6
    ],
    [
        'id' => 'b',
        'weight' => 2,
        'money' => 3
    ],
    [
        'id' => 'c',
        'weight' => 6,
        'money' => 5
    ],
    [
        'id' => 'd',
        'weight' => 5,
        'money' => 4
    ],
    [
        'id' => 'e',
        'weight' => 4,
        'money' => 6
    ]
];
 
$pack = 10;
 
$result = [];
 
$max = ['money' => 0];
 
foreach ($list as $item) {
    $process = [
        'count' => $item['weight'],
        'money' => $item['money'],
        'list' => [$item]
    ];
    foreach ($list as $_item) {
        if ($_item !== $item) {
            if ($process['count'] + $_item['weight'] <= $pack) {
                $process['count'] += $_item['weight'];
                $process['money'] += $_item['money'];
                $process['list'][] = $_item;
            }
        }
        if ($process['count'] === $pack) break;
    }
    $result[] = $process;
    if ($max['money'] < $process['money']) $max = $process;
}
 
//全部组合
print_r($result);
 
//价值最大组合
print_r($max);