// 动态规划
error_reporting(E_ALL ^ E_NOTICE);
$t1= microtime(true);
classbestMatch
{
publicfunctiongetMethod($postData)
{
$peopleArr= $gainArr= $nameArr= [0];
foreach($postData['carDetail'] as$val) {
// 初始化各个套餐:所需人数、利润和套餐名称数组
$peopleArr[] = $val['technician'];
$gainArr[] = $val['amount'];
$nameArr[] = $val['type'];
}
// 获取人数总数(背包)
$totalPeople= $postData['people'];
// 做检测单数
$items= count($peopleArr);
// 利润列表 - 初始状态
$cacheMap[] = array_fill(1, $items, 0);
// 套餐列表 - 初始状态
$cacheMapName[] = array_fill(1, $items, '');
//中间的各种决策(依次放入物品a,b,c,d,e)
// 第一个循环是总人数
for($i= 1; $i<= $totalPeople; $i++)
{
// 第二个循环是套餐
for($j= 1; $j< $items; $j++)
{
$requiredPeople= $peopleArr[$j];
$gain= $gainArr[$j];
$name= $nameArr[$j];
// 上一行坐标数
$preLine= $j-1;
$prevGain= $cacheMap[$preLine][$i];
$prevName= $cacheMapName[$preLine][$i];
if($requiredPeople> $i)
{
$cacheMap[$j][$i] = $prevGain;
$cacheMapName[$j][$i] = $prevName;
}
else
{
// 剩余价值
if($i-$requiredPeople>= 0) {
$surplusPeople= $i-$requiredPeople;
$surplusGain= $cacheMap[$preLine][$surplusPeople];
$surplusName= $cacheMapName[$preLine][$surplusPeople];
}else{
$surplusGain= 0;
$surplusName= '';
}
$nowTotalGain= $gain+ $surplusGain;
$cacheMap[$j][$i] = max($prevGain, $nowTotalGain);
if($prevGain> $nowTotalGain) {
$cacheMapName[$j][$i] = $prevName;
}else{
$cacheMapName[$j][$i] = $name.'+'.$surplusName;
}
}
}
}
$actual= count($postData['carDetail']);
return[
'maxMatch'=> $cacheMap[$actual][$totalPeople],
'maxMatchName'=> trim($cacheMapName[$actual][$totalPeople],'+')
];
}
}
$bestMatch= newbestMatch;
if(empty($_POST) || isset($_POST['people']) && $_POST['people'] > 0) {
die('提交参数有误');
}
$res= $bestMatch->getMethod($_POST);
$t2= microtime(true);
echo'动态规划: '.'
';
echo'最佳金额: '.$res['maxMatch'].'
';
echo'最佳套餐搭配: '.$res['maxMatchName'].'
';
echo'耗时'.round($t2-$t1,7).'秒'.'
';
echo'消耗内存: '. memory_get_usage().'字节'.'
';