有两艘船需要装运的n箱货物,第一艘船的载重量是c1,第二艘船的载重量是c2,wi是货箱i的重量,且w1+w2+……+wn<=c1+c2

(1) 问题描述: 
       有两艘船和需要装运的n个货箱,第一艘船的载重量是c1,第二艘船的载重量是c2,wi是货箱的质量,且w1+w2+...+wn <= c1+c2. 
希望确定是否有一种可将所有n个货箱全部装船的方法。若有的话,找出该方法。

(2) 举例描述: 
       当n=3,c1=c2=50,w=[10,40,40]时,可将货箱1、2装到第一艘船上,货箱3装到第二艘船上。 
       但是如果w=[20,40,40],则无法将货箱全部装船。由此可知问题可能有解,可能无解,也可能有多解。 
   
(3) 问题分析 
       虽然是关于两艘船的问题,其实只讨论一艘船的最大装载问题即可。因为当第一艘船的最大装载为bestw时, 
若w1+w2+...+wn-bestw <= c2,则可以确定一种解,否则问题就无解。这样的问题转化为第一艘船的最大装载问题。

(4) 算法设计 
       转化为一艘船的最优化问题后, 问题的解空间为一个子集树。也就是算法要考虑所有物品取、舍情况的组合, 
n个物品的取舍组合共有2的n次方个分支。

1> 和回溯算法的思想一样,用FIFO分支搜索所有的分支,并记录已搜索分支的最优解,搜索完子集树也就找出了问题的解。 
   
       2> 要想求出最优解,必须搜索到叶结点,所以要记录数的层次。当层次为n+1时,搜索完全部叶结点,算法结束。

3> 分支搜索过程中活结点的"层"是需要标识的,否则入队后无法识别结点所在的层。每处理完一层让"-1"入队,以此来标识 
          "层",并用变量i来记录当前层。

4> 每个活结点要记录当前船的装载量。

代码示例:

 <?php
class Queue
{
private $queue = array(); /**
* 入栈
*/
public function push($val)
{
array_push($this->queue, $val);
} /**
* 出栈
*/
public function pop()
{
$value = array_shift($this->queue);
return $value;
} /**
* 判断是否为空栈
*/
public function is_empty()
{
if(empty($this->queue))
{
return true;
} else {
return false;
}
}
} class BranchLimitFIFOSearch
{
private $n;//n个货箱
private $c1;//第一艘船的载重量
private $c2;//第二艘船的载重量
private $bestw;//第一艘船的最大载量
private $ew = 0;//当前船的装载量
private $w;//货箱质量数组 array
private $s = 0;//所有货箱的重量之后
private $queue;//FIFO队列 /**
* 构造函数
*/
public function __construct($n, $c1, $c2, $w)
{
$this->n = $n;
$this->c1 = $c1;
$this->c2 = $c2;
$this->w = $w;
$this->s = is_array($w) ? array_sum($w) : 0;
$this->queue = new Queue();
} /**
* 最忧装载值
* @param $c 第一艘船的载重量
*/
public function max_loading($c)
{
$i = 1;//E-节点的层
$this->ew = 0;//当前船的装载量
$this->bestw = 0;//目前的最优值
$this->queue->push(-1); while(!$this->queue->is_empty())//搜索子集空间树
{
if($this->ew + $this->w[$i] <= $c)//检查E-节点的左孩子,货箱i是否可以装载
{
$this->add_live_node($this->ew + $this->w[$i], $i);//货箱i可以装载
}
$this->add_live_node($this->ew, $i); $this->ew = $this->queue->pop();//取下一个节点 if(-1 == $this->ew)
{
if($this->queue->is_empty())
{
break;
}
$this->queue->push(-1);
$this->ew = $this->queue->pop();//取下一个节点
$i++;
}
} return $this->bestw;
} /**
* 入队
*/
public function add_live_node($wt, $i)
{
if($this->n == $i)//是叶子
{
$this->bestw < $wt && $this->bestw = $wt;
} else {//不是叶子
$this->queue->push($wt);
}
} /**
* 所有货箱的重量
*/
public function get_s()
{
return $this->s;
} /**
* 获取最优值
*/
public function get_bestw()
{
return $this->bestw;
}
} function branch_limit_FIFO_search()
{
$n = 3;
$c1 = 50;
$c2 = 50;
$w = array(0,10,40,40);
$bfis = new BranchLimitFIFOSearch($n, $c1, $c2, $w);
$s = $bfis->get_s();//所有货箱的重量之后 if($s<=$c1 || $s<=$c2)
{
die("need only one ship!");
}
if($s > $c1+$c2)
{
die("no solution!");
} $bfis->max_loading($c1);
$bestw = $bfis->get_bestw();
if($s-$bestw <= $c2)
{
echo "The first ship loading " . $bestw . "<br/>";
echo "The second ship loading " . ($s - $bestw);
} else {
echo "no solution!!!";
}
} branch_limit_FIFO_search();
上一篇:asp.net 短信群发


下一篇:IOS uitableviewcell 向左滑动删除编辑等