Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use greedy algorithm to solve 0-1 knapsack problem in PHP

Shulou Source: shulou.com Published: 2022-06-03 19:45:52 10月03日 Update

This article mainly shows you "PHP how to use greedy algorithm to solve 0-1 knapsack problem", the content is easy to understand, clear, hope to help you solve doubts, the following let the editor lead you to study and learn "PHP how to use greedy algorithm to solve 0-1 knapsack problem" this article.

The specific analysis is as follows:

Greedy algorithm to solve the 0-1 knapsack problem, the global optimal solution through the local optimal solution to obtain! More flexible than dynamic programming to solve knapsack problems!

/ / 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 $nasty 10 for ($val- > price; echo')

';}} / / sort function tsort (& $x) {$len=count ($x) by price and weight ratio; for ($temres=$temp- > price/$temp- > weight; if ($res > $temres) {$x [$j] = $x [$temp;]}} / / greedy algorithm function tanxin ($len=count ($x) ($totalweight) 50) {$len=count ($x); $allprice=0; for ($iTotalweightweight > $totalweight) break Else {$allprice+=$x [$I]-> price; $totalweight=$totalweight-$x [$I]-> weight;}} if ($iprice* ($totalweight/$x [$I]-> weight); return $allprice;} tsort ($x); / / sort display ($x) in non-incremental order; / / display echo'0-1 knapsack optimal solution is:'; echo tanxin ($x) These are all the contents of the article "how PHP uses greedy algorithms to solve the 0-1 knapsack problem". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Backpacks algorithms problems greed content articles learning help sorting price global dynamic local data easy to understand more organization order knowledge editing Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple Linux vpn Docker Redmi