This article describes the PHP greedy algorithm to solve the 0-1 knapsack problem method. Share to everyone for your reference. The specific analysis is as follows:
The greedy algorithm solves 0-1 knapsack problem, and the global optimal solution is obtained by local optimal solution. More flexible than dynamic planning to solve knapsack problem!
0-1 knapsack greedy algorithm problem class tanxin{public $weight;
Public $price;
Public function __construct ($weight =0, $price =0) {$this->weight= $weight;
$this->price= $price;
}//Generate Data $n = 10;
for ($i =1; $i <= $n; $i + +) {$weight =rand (1,20);
$price =rand (1,10);
$x [$i]=new tanxin ($weight, $price);
//Output result function display ($x) {$len =count ($x);
foreach ($x as $val) {echo $val->weight, ', $val->price;
Echo ' <br> ';
}//ORDER by price and weight ratio tsort (& $x) {$len =count ($x);
For ($i =1 $i <= $len $i + +) {for ($j =1; $j <= $len-$i; $j + +) {$temp = $x [$j];
$res = $x [$j +1]->price/$x [$j +1]->weight;
$temres = $temp->price/$temp->weight;
if ($res > $temres) {$x [$j]= $x [$j +1];
$x [$j +1]= $temp;
}}//greedy algorithm function tanxin ($x, $totalweight =50) {$len =count ($x);
$allprice = 0;
For ($i =1 $i <= $len $i + +) {if ($x [$i]->weight> $totalweight) break;
else{$allprice + + $x [$i]->price; $totalweight = $totalweight-$x [$i]->weight;
} if ($i < $len) $allprice + = $x [$i]->price* ($totalweight/$x [$i]->weight);
return $allprice;
Tsort ($x);//order display ($x) in a non increment order;//show Echo ' 0-1 The best solution is: '; echo tanxin ($x);
I hope this article will help you with your PHP programming.