回溯算法,非算法高手勿进!
<br /> <?php<br /> $m = 15;<br /> $arr = array(array(2,1),array(4,2),array(3,6),array(5,9),array(9,8));//第一个值为价格 ;第二个值为 重量<br /> function Combination($arr, $size = 1) {<br /> $len = count ( $arr );<br /> $max = pow ( 2, $len ) - pow ( 2, $len - $size );<br /> $min = pow ( 2, $size ) - 1;<br /> $r_arr = array ();<br /> for($i = $min; $i <= $max; $i ++) {<br /> $t_arr = array ();<br /> for($j = 0,$k = 0; $j < $len; $j ++) {<br /> $a = pow ( 2, $j );<br /> $t = $i & $a;<br /> if ($t == $a) {<br /> $t_arr [] = $arr [$j];<br /> }<br /> }<br /> if (count($t_arr) == $size) {<br /> $r_arr [] = $t_arr;<br /> }<br /> }<br /> return $r_arr;<br /> }<br /> $num = count($arr);<br /> for($i = 1;$i<=$num;$i++){<br /> $_tt = Combination($arr,$i);<br /> $num_tt = count($_tt);<br /> for($j = 0;$j<$num_tt;$j++){<br /> $_t[] = $_tt[$j];<br /> }<br /> }//找出所以的可能情况<br /> function check_m($arr,$m,$jk=1) {//$arr 为要判断的数组 $m为重量 $jk为判断的是重量还是价格<br /> $num_t = count($arr);<br /> for($i = 0;$i <$num_t ;$i++){<br /> $num_ti = count($arr[$i]);<br /> $as = 0;<br /> for($j=0;$j<$num_ti;$j++){<br /> $as += $arr[$i][$j][$jk];<br /> }<br /> if($as<=$m){<br /> $_r[] =$arr[$i];<br /> }<br /> }<br /> Return $_r;<br /> }<br /> <br /> <br /> function check_max($arr) {<br /> $ms = 0;<br /> $num_t = count($arr);<br /> for($i = 0;$i <$num_t ;$i++){<br /> $num_ti = count($arr[$i]);<br /> $as = 0;<br /> for($j=0;$j<$num_ti;$j++){<br /> $as += $arr[$i][$j][0];<br /> }<br /> if($as>=$ms){<br /> $_r = $arr[$i];<br /> }<br /> $ms = $as;<br /> }<br /> Return $_r;<br /> }<br /> $_rr = check_m($_t,$m,1);<br /> $_r=check_max($_rr);<br /> echo "<pre class="brush:php;toolbar:false">";<br /> print_r($_r);<br /> echo "";
class Backtracking { <br> private $c = 0; //背包容量 <br> private $n = 0; //物品数 <br> private $w = array(); //物品重量数组 <br> private $p = array(); //物品价值数组 <br> private $cw = 0; //当前重量 <br> private $cp = 0; //当前价值 <br> private $bestp = 0; //当前最优价值 <br> private $d; //单位重量价值<br> private $st = array();<br> <br> function __construct($w, $p, $c) {<br> $this->w = $w;<br> $this->p = $p;<br> $this->c = $c;<br> $this->n = count($w);<br> <br> $this->d = array_map(array($this, 'Calculation'), $this->p, $this->w);<br> array_multisort($this->d, SORT_DESC, $this->w, $this->p);<br> }<br> <br> private function Calculation($p, $w) {<br> if($w == 0) return $p; <div class="clear"> </div>