Bridge problem:
In the dark of night, four travelers came to a narrow bridge with no guardrail. Without the help of a flashlight, we would not have dared to cross the bridge anyway. Unfortunately, four people took only one flashlight, and the bridge was narrow enough for two people to cross. If they cross the bridge alone, the four people will need 1, 2, 5, 7 minutes respectively, and if the two people cross the bridge at the same time, it takes the slower the person to take the time to act alone. The question is how to design a plan to get the four people across the bridge as quickly as possible.
PHP Code:
<?php
//////////////////////////////
Author: Wandering a niche/////
www.cnphper.com////
PHP solves bridge problem////
///////////////////////////
$data = Array (1,2,5,9)//$data the number of elements in the array is corresponding to the numbers of the bridge, can be arbitrarily modified (>1)
Sort_data ($data);
$num = count ($data);
if ($num = = 2)
{
$costtime = $data [1];
}
ElseIf ($num = = 3)
{
$costtime = 2* $data [0]+ $data [1]+ $data [2];
}
ElseIf ($num > 3)
{
$costtime = Get_result ($data, $num, 0);
}
echo "The shortest time to cross the bridge". $costtime;
function Get_result ($data, $num, $costtime)
{
if (2* $data [1]< $data [0]+ $data [$num-2])
{
$costtime + + 2* $data [1]+ $data [0]+ $data [$num-1];
Array_pop ($data);
Array_pop ($data);
$num = count ($data);
if ($num >3)
{
Get_result ($data, $num, $costtime);
}
ElseIf ($num ==3)
{
$costtime + + 2* $data [0]+ $data [1]+ $data [2];
return $costtime;
}
ElseIf ($num ==2)
{
$costtime + + $data [1];
return $costtime;
}
}
Else
{
$costtime + + 2* $data [0]+ $data [$num -2]+ $data [$num-1];
Array_pop ($data);
Array_pop ($data);
$num = count ($data);
if ($num >3)
{
Get_result ($data, $num, $costtime);
}
ElseIf ($num ==3)
{
$costtime + + 2* $data [0]+ $data [1]+ $data [2];
return $costtime;
}
ElseIf ($num ==2)
{
$costtime + + $data [1];
return $costtime;
}
}
}
Function Sort_data (& $data)
{
Sort ($data);
Reset ($data);
}
?>