ウィキペディアによると
このパズルは、1981 年に『パズルとゲームの超戦略』という本に登場したことが知られています。このバージョンのパズルでは、A、B、C、D が交差するのにそれぞれ 5、10、20、25 分かかり、制限時間は 60 分です。
しかし、この質問は、「富士山をどのように動かしますか?」という本に登場した後、広く知られるようになりました。
この質問は、橋を渡るのにかかる個々の時間が異なる N 人について一般化することができます。
以下のプログラムは、一般的な N 人の人とその時間に対して機能します。
class Program
{
public static int TotalTime(List<int> band, int n)
{
if (n < 3)
{
return band[n - 1];
}
else if (n == 3)
{
return band[0] + band[1] + band[2];
}
else
{
int temp1 = band[n - 1] + band[0] + band[n - 2] + band[0];
int temp2 = band[1] + band[0] + band[n - 1] + band[1];
if (temp1 < temp2)
{
return temp1 + TotalTime(band, n - 2);
}
else if (temp2 < temp1)
{
return temp2 + TotalTime(band, n - 2);
}
else
{
return temp2 + TotalTime(band, n - 2);
}
}
}
static void Main(string[] args)
{
// change the no of people crossing the bridge
// add or remove corresponding time to the list
int n = 4;
List<int> band = new List<int>() { 1, 2, 5, 10 };
band.Sort();
Console.WriteLine("The total time taken to cross the bridge is: " + Program.TotalTime(band, n));
Console.ReadLine();
}
}
出力:
橋を渡るのにかかった合計時間: 17
為に、
int n = 5;
List<int> band = new List<int>() { 1, 2, 5, 10, 12 };
出力:
橋を渡るのにかかった合計時間: 25
為に、
int n = 4;
List<int> band = new List<int>() { 5, 10, 20, 25 };
OUTPUT 橋を渡るのにかかった合計時間: 60