时间:2021-07-01 10:21:17 帮助过:30人阅读
你遇到了什么问题呢?你的结果应该是对的
不过我喜欢这么写
$w = 10;$ar = array( array('w' => 3, 'v' => 4), array('w' => 4, 'v' => 5), array('w' => 5, 'v' => 6),);foreach($ar as $k=>$v) { $v['k'][] = $k; $res[] = $v;}$p = 0;for(;$p$v) { if(in_array($i, $res[$p]['k'])) continue; if($r['w'] + $v['w'] <= $w) { $res[] = array( 'w' => $r['w'] + $v['w'], 'v' => $r['v'] + $v['v'], 'k' => array_merge($r['k'], array($i)), ); } }}foreach($res as $v) $t[] = $v['v'];array_multisort($t, SORT_DESC, $res); print_r($res);
Array( [0] => Array ( [w] => 9 [v] => 11 [k] => Array ( [0] => 1 [1] => 2 ) ) [1] => Array ( [w] => 9 [v] => 11 [k] => Array ( [0] => 2 [1] => 1 ) ) [2] => Array ( [w] => 8 [v] => 10 [k] => Array ( [0] => 0 [1] => 2 ) ) [3] => Array ( [w] => 8 [v] => 10 [k] => Array ( [0] => 2 [1] => 0 ) ) [4] => Array ( [w] => 7 [v] => 9 [k] => Array ( [0] => 0 [1] => 1 ) ) [5] => Array ( [w] => 7 [v] => 9 [k] => Array ( [0] => 1 [1] => 0 ) ) [6] => Array ( [w] => 5 [v] => 6 [k] => Array ( [0] => 2 ) ) [7] => Array ( [w] => 4 [v] => 5 [k] => Array ( [0] => 1 ) ) [8] => Array ( [w] => 3 [v] => 4 [k] => Array ( [0] => 0 ) ))
目前这个是 装满了w=10的背包的最大价值。
我是想找出:在尽量装满背包的情况下,总价值接近给定的一个阈值T 的组合
$f = 9;print_r(array_filter($res, function($a) use ($f) { return $a['v'] > 0.9*$f && $a['v']<1.1*$f;}));
太强了,感谢版主大人!非常牛B,结果完全达到了
这个算法你写的太简洁了,有点看不懂,再请教您一下,怎么过滤掉重复的组合啊? 比如 0 3 6 ,3 0 6,6 0 3
....array_multisort($t, SORT_DESC, $res); //排序(已有的)foreach($res as $i=>$v) if(isset($res[$i-1]) && ! array_diff($res[$i-1]['k'], $v['k'])) unset($res[$i]); //去重$res = array_values($res); //规格化
太感谢了,多谢您的指教