本文共 2955 字,大约阅读时间需要 9 分钟。
7.设有n 种物品,每种物品有一个重量及一个价值。但每种物品的数量是无限的,同时有一个背包,
最大载重量为M,今从n 种物品中选取若干件(同一种物品可以多次选取),使其重量的和小于等于M,
而价值的和为最大。
- <?php
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- $params=getParams(2);
- $argv0=trim(trim($params[0]),";");
- $argv1=trim($params[1]);
-
- if(!preg_match_all("/^((\d+,\d+);?)+$/i", $argv0,$matches))
- {
- error_msg("params 1 must is group of numbers,break with ; and ,");
- }
-
- if(!is_numeric($argv1))
- {
- error_msg("params 3 must be a numbers");
- }
- $weights=array();
- $values=array();
- $a=split(";",trim($argv0, ";"));
- foreach($a as $s)
- {
- $b=split(",",trim($s, ","));
- $weights[]=$b[0];
- $values[]=$b[1];
- }
-
-
- if(count($weights)!=count($values))
- {
- error_msg("weights count must equal values count");
- }
- $max_weight=$argv1;
-
- $value_per_weights=array();
- foreach($weights as $i => $weight)
- {
- if($weight==0)
- {
- error_msg("weight must > 0");
- }
- $value_per_weights[$i]=$values[$i]/$weight;
- }
-
- $ar = array ($value_per_weights, $weights,$values,array_keys($values));
- array_multisort ($ar[0],SORT_NUMERIC, SORT_DESC,
- $ar[1], SORT_NUMERIC, SORT_ASC,
- $ar[2], SORT_NUMERIC, SORT_DESC,$ar[3]);
-
- $weights_order=$ar[1];
- $values_order=$ar[2];
- $index_order=$ar[3];
- $now_weight=0;
- $i=0;
- $total=count($weights_order);
- $max_value=0;
- $find=array();
- while(1)
- {
- if($now_weight+$weights_order[$i] <= $max_weight)
- {
- $now_weight+=$weights_order[$i];
- $max_value+=$values_order[$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;
- }
- }
- }
-
- output("",true);
- if(count($find)==0)
- {
- output("max weight too small",true);
- error_msg("execute success");
- }
-
- output("weight:$now_weight;max value:$max_value");
- foreach($find as $index => $num)
- {
- output("物品 $index(".$weights[$index].",".$values[$index].") 的个数:$num");
- }
- error_msg("execute success");
-
-
-
-
-
- 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;
- }
-
-
-
-
-
- function output($msg,$isClean=false)
- {
- if($isClean)
- {
- $handle = fopen('out.txt', 'w');
- fclose($handle);
- }
- error_log($msg."\n", 3, "out.txt");
- }
-
-
-
-
- function error_msg($msg,$is_exit=true)
- {
- if($is_exit)
- die($msg."\n");
- else
- echo $msg."\n";
- }
- ?>
转载地址:http://dfxxa.baihongyu.com/