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;$iweight,' ',$val->price;
echo '<br>';
}
}
//按照价格和重量比排序
function tsort(&$x)
{
$len=count($x);
for($i=1;$iprice/$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;$iweight>$totalweight) break;
else{
$allprice+=$x[$i]->price;
$totalweight=$totalweight-$x[$i]->weight;
}
}
if($iprice*($totalweight/$x[$i]->weight);
return $allprice;
}
tsort($x);//按非递增次序排序
display($x);//显示
echo '0-1背包最优解为:';
echo tanxin($x);
使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!










