13:有一艘大船准备用来装载货物。所有待装货物都装在货箱中且所有货箱的大小都一样,
但货箱的重量都各不相同。设第i 个货箱的重量为wi(1≤i≤n),
而货船的最大载重量为c,如何在货船上装入最多的货物。
- <?php
- /*
- *13:有一艘大船准备用来装载货物。所有待装货物都装在货箱中且所有货箱的大小都一样,
- 但货箱的重量都各不相同。设第i 个货箱的重量为wi(1≤i≤n),
- 而货船的最大载重量为c,如何在货船上装入最多的货物。
- *系统环境:windows/linux
- *编译环境:php4/php5
- *输入参数:存放在in.txt,多个参数时空格分隔
- 参数1是一组数字,表示一组物品的重量 中间用分号分割;
- 重量,单位为千克,不能有0
- 参数3是一个数字,表示最大重量,单位为千克,
- 例如格式:8,2,11,3,7 13
- 输出:out.txt
- */
- $params=getParams(2);
- $argv0=trim(trim($params[0]),",");
- $argv1=trim($params[1]);
- //检查参数1
- if(!preg_match_all("/^(\d+,?)+$/i", $argv0,$matches))
- {
- error_msg("params 1 must is group of numbers,break with ; and ,");
- }
- //检查参数2
- if(!is_numeric($argv1))
- {
- error_msg("params 2 must be a numbers");
- }
- $weights=split(",",trim($argv0, ","));
- $max_weight=$argv1;
- foreach($weights as $weight)
- {
- if($weight==0)
- error_msg("weight must > 0");
- }
- $ar = array ($weights,array_keys($weights));
- //按照重量从小到大排序
- array_multisort($ar[0],SORT_NUMERIC, SORT_ASC,$ar[1]);
- $weights_order=$ar[0];
- $index_order=$ar[1];
- $now_weight=0;
- $i=0;
- $total=count($weights_order);
- $find=array();
- while(1)
- {
- if($now_weight+$weights[$i] <= $max_weight)
- {
- $now_weight+=$weights_order[$i];
- //统计物品i的个数
- if(isset($find[$index_order[$i]]))
- {
- $find[$index_order[$i]]++;
- }else
- {
- $find[$index_order[$i]]=1;
- }
- if($now_weight==$max_weight)
- {
- break;
- }
- }else{
- $i++;
- if($i >= $total)
- {
- break;
- }
- }
- }
- //清空out.txt
- output("",true);
- if(count($find)==0)
- {
- output("max weight too small",true);
- error_msg("execute success");
- }
- //输出结果
- output("weight:$now_weight;");
- foreach($find as $index => $num)
- {
- output("物品 ".($index+1)."(".$weights[$index].") 的个数:$num");
- }
- error_msg("execute success");
- /*
- 从in.txt里读取参数
- */
- function getParams($paramNum)
- {
- $in=file_get_contents("in.txt");
- if($in===FALSE){
- error_msg("cannot read in.txt,please check in.txt exists\n");
- }
- $in=preg_replace("/(\s+)/i", " ", $in);
- //多个参数时,按照空格分隔
- $parms=split(" ",trim($in));
- if($parms===FALSE)
- {
- error_msg("cannot get param from in.txt\n");
- }
- if(count($parms) < $paramNum)
- {
- error_msg("it needs $paramNum params\n");
- }
- return $parms;
- }
- /*
- 把结果输出到输出文件里
- 当isClean=true时清空out.txt
- */
- function output($msg,$isClean=false)
- {
- if($isClean)
- {
- $handle = fopen('out.txt', 'w');
- fclose($handle);
- }
- error_log($msg."\n", 3, "out.txt");
- }
- /*
- 输入错误信息
- 如果$is_exit表示输入信息后退出
- */
- function error_msg($msg,$is_exit=true)
- {
- if($is_exit)
- die($msg."\n");
- else
- echo $msg."\n";
- }
- ?>