PHP貪婪演算法解決0-1背包問題執行個體分析_php技巧

來源:互聯網
上載者:User

本文執行個體講述了PHP貪婪演算法解決0-1背包問題的方法。分享給大家供大家參考。具體分析如下:

貪心演算法解決0-1背包問題,全域最優解通過局部最優解來獲得!比動態規劃解決背包問題更靈活!

//0-1背包貪心演算法問題class tanxin{  public $weight;  public $price;  public function __construct($weight=0,$price=0)  {    $this->weight=$weight;    $this->price=$price;  }}//產生資料$n=10;for($i=1;$i<=$n;$i++){  $weight=rand(1,20);  $price=rand(1,10);  $x[$i]=new tanxin($weight,$price);}//輸出結果function display($x){  $len=count($x);  foreach($x as $val){    echo $val->weight,' ',$val->price;    echo '<br>';  }}//按照價格和重量比排序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;      }    }  } }//貪心演算法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);//按非遞增次序排序display($x);//顯示echo '0-1背包最優解為:';echo tanxin($x);

希望本文所述對大家的php程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.