PHP贪婪算法解决0-1背包问题实例分析

yipeiwu_com5年前PHP代码库

本文实例讲述了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程序设计有所帮助。

相关文章

在windows平台上构建自己的PHP实现方法(仅适用于php5.2)

构建步骤1, 安装vs20082, 安装windows sdk 6.13, 下载php 5.2源码,可以从此处获取Releases (先不要解压)4, 下载bindlib_w32.zip...

处理(php-cgi.exe - FastCGI 进程超过了配置的请求超时时限)的问题

【详细错误】:HTTP 错误 500.0 - Internal Server ErrorC:\Program Files\PHP\php-cgi.exe - FastCGI 进程超过了配...

php中Y2K38的漏洞解决方法实例分析

本文实例分析了php中Y2K38漏洞的解决方法。分享给大家供大家参考。具体分析如下: Y2K38,又称 Unix Millennium Bug, 此漏洞将会影响到所有 32 位系统下用...

PHP 柱状图实现代码

PHP 柱状图实现代码

还有疑问的朋友可以加我QQ:460634320,大家一起讨论。 效果图:复制代码 代码如下: <?php function createImage($data,$twidth,$t...

探讨PHP中this,self,parent的区别详解

{一}PHP中this,self,parent的区别之一this篇面向对象编程(OOP,Object OrientedProgramming)现已经成为编程人员的一项基本技能。利用OOP...