国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發(fā) > PHP > 正文

PHP貪婪算法解決0-1背包問題實(shí)例分析

2024-05-04 23:33:12
字體:
供稿:網(wǎng)友

這篇文章主要介紹了PHP貪婪算法解決0-1背包問題,實(shí)例分析了貪婪算法的原理與背包問題的實(shí)現(xiàn)技巧,需要的朋友可以參考下

本文實(shí)例講述了PHP貪婪算法解決0-1背包問題的方法。分享給大家供大家參考。具體分析如下:

貪心算法解決0-1背包問題,全局最優(yōu)解通過局部最優(yōu)解來獲得!比動(dòng)態(tài)規(guī)劃解決背包問題更靈活!

 

 
  1. //0-1背包貪心算法問題 
  2. class tanxin{ 
  3. public $weight
  4. public $price
  5. public function __construct($weight=0,$price=0) 
  6. $this->weight=$weight
  7. $this->price=$price
  8. //生成數(shù)據(jù) 
  9. $n=10; 
  10. for($i=1;$i<=$n;$i++){ 
  11. $weight=rand(1,20); 
  12. $price=rand(1,10); 
  13. $x[$i]=new tanxin($weight,$price); 
  14. //輸出結(jié)果 
  15. function display($x
  16. $len=count($x); 
  17. foreach($x as $val){ 
  18. echo $val->weight,' ',$val->price; 
  19. echo '<br>'
  20. //按照價(jià)格和重量比排序 
  21. function tsort(&$x
  22. $len=count($x); 
  23. for($i=1;$i<=$len;$i++) 
  24. for($j=1;$j<=$len-$i;$j++) 
  25. {  
  26. $temp=$x[$j]; 
  27. $res=$x[$j+1]->price/$x[$j+1]->weight; 
  28. $temres=$temp->price/$temp->weight; 
  29. if($res>$temres){ 
  30. $x[$j]=$x[$j+1]; 
  31. $x[$j+1]=$temp
  32. }  
  33. //貪心算法 
  34. function tanxin($x,$totalweight=50) 
  35. $len=count($x); 
  36. $allprice=0; 
  37. for($i=1;$i<=$len;$i++){ 
  38. if($x[$i]->weight>$totalweightbreak
  39. else
  40. $allprice+=$x[$i]->price; 
  41. $totalweight=$totalweight-$x[$i]->weight; 
  42. if($i<$len$allprice+=$x[$i]->price*($totalweight/$x[$i]->weight); 
  43. return $allprice
  44. tsort($x);//按非遞增次序排序 
  45. display($x);//顯示 
  46. echo '0-1背包最優(yōu)解為:'
  47. echo tanxin($x); 

希望本文所述對(duì)大家的php程序設(shè)計(jì)有所幫助。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 松桃| 阳原县| 集安市| 尼木县| 溆浦县| 两当县| 沂南县| 措勤县| 武川县| 宁都县| 沂水县| 承德县| 金沙县| 宽城| 历史| 尼玛县| 灌南县| 大洼县| 石阡县| 乌鲁木齐市| 郴州市| 霸州市| 黄冈市| 浦东新区| 陇川县| 滦平县| 襄汾县| 横峰县| 房产| 胶州市| 云南省| 从化市| 凤凰县| 双城市| 闻喜县| 德庆县| 和田县| 沾益县| 澳门| 建瓯市| 江门市|