Home >Backend Development >PHP Tutorial >PHP greedy algorithm to solve the 0-1 knapsack problem example analysis_PHP tutorial
This article mainly introduces the PHP greedy algorithm to solve the 0-1 knapsack problem, and analyzes the principles and principles of the greedy algorithm with examples. Friends who need the implementation skills of the knapsack problem can refer to it
The example in this article describes the method of PHP greedy algorithm to solve the 0-1 knapsack problem. Share it with everyone for your reference. The specific analysis is as follows:
The greedy algorithm solves the 0-1 knapsack problem, and the global optimal solution is obtained through the local optimal solution! More flexible than dynamic programming to solve the knapsack problem!
?
|
//0-1 backpack 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 results<🎜>
<🎜>function display($x)<🎜>
<🎜>{<🎜>
<🎜>$len=count($x);<🎜>
<🎜>foreach($x as $val){<🎜>
<🎜>echo $val->weight,' ',$val->price;
echo ' '; } } //Sort by price and weight ratio function 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);//Sort in non-increasing order display($x);//Display echo 'The optimal solution for the 0-1 backpack is:'; echo tanxin($x); |
I hope this article will be helpful to everyone’s PHP programming design.