题目:共有25匹马,有一个赛场,赛场有5个赛道,就是说最多同时可以有5匹马一起比赛。假设每匹马都跑的很稳定,不用任何其他工具,只通过马与马之间的比赛,试问最少得比多少场才能知道跑得最快的5匹马。
算法分析:
先分5组(a b c d e组)跑5场
第1场:a组的:比赛结果如下:a1, a2, a3, a4, a5
接下来四场分别是b,c,d,e组各自比赛,结果由名次由下标体现
第6场:a2,b2, c2, d2, e2
无论哪组胜出,该组的第一名肯定在跑得最快的五匹里max{ ×,×,×,×,× }。
不妨假设a2胜出,则至此得出max{ a1,×,×,×,× }
第7场:a2,b1,c1,d1, e1
1)a2胜出,max{ a1,a2,×,×,× },下一场a3,b1,c1,d1, e1
2)不是a2胜出,max{ a1,b1,×,×,× } 下一场 a2,b2,c1,d1, e1
以后几场分别根据前次比赛结果,选获胜组中的次快马代替获胜马,进行与第7场同样的处理。
直到max里有5匹马。从第六场开始,每一场比赛都将选出一匹当前最快的马。
(举其中一种情况作为例子)
8:a3,b1,c1,d1, e1
处理方法跟第七场相同(该场后max至少有3个元素)
9:a4,b1,c1,d1, e1
处理方法跟第七场相同(该场后max至少有4个元素)
10:a5,b1,c1,d1, e1
处理方法跟第七场相同(该场后max至少有5个元素) 结束(共10场)
代码如下:
using System;
public class HorseRace
{
private int[,] horses = new int[5,5];
public HorseRace()
{
//initialize horses speeds with a Random instance.
Random rd = new Random();
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
horses[i, j] = rd.Next(1,60000);//suppose horse fastest speed is 60km/h
}
}
}
//sort each group's horses by their speeds
public void ARace(int[,] k)
{
for (int l = 0; l < 5; l++)
{
for (int i = 0; i < 5; i++)
{
for (int j = i + 1; j < 5; j++)
{
if (k[l, i] < k[l, j])
{
k[l, i] = k[l, i] + k[l, j];
k[l, j] = k[l, i] - k[l, j];
k[l, i] = k[l, i] - k[l, j];
}
}
}
}
}
//find the fastest horse, then return the group number.
public int Max(int[] k)
{
int max = 0;
for (int i = 1; i < 5; i++)
{
if (k[i] > k[max])
{
max = i;
}
}
return max;
}
//print the horses, one row one group.
public void Print()
{
System.Console.WriteLine("=====================================");
for (int i = 0; i < 5; i++)
{
System.Console.Write("|");
for (int j = 0; j < 5; j++)
{
System.Console.Write("{0,5}==", horses[i, j]);
}
System.Console.Write("|");
System.Console.WriteLine(" ");
}
System.Console.WriteLine("=====================================");
}
public void Fifth()
{
for (int i = 0; i < 5; i++)
{
ARace(horses);
}
int[] temp = new int[5];//store the speeds of horses who want to race next.
//choose the second horse for race.
for (int i = 0; i < 5; i++)
{
temp[i] = horses[i, 1];
}
int mm = Max(temp);//find the win group.
int[] m = new int[5];//store the next horse(NO.) which want to race representive the current win group.
m[mm] = 1;
System.Console.Write("The dark horses are: {0,7}", horses[mm, 0]);
for (int i = 0; i < 5; i++)
{
if (i != mm)
{
temp[i] = horses[i, 0];
}
}
int count = 1;
while (5 > count++)
{
mm = Max(temp);
System.Console.Write("{0,7}", horses[mm, m[mm]++]);
temp[mm] = horses[mm, m[mm]];
}
}
public static void Main()
{
HorseRace h = new HorseRace();
h.Print();
h.Fifth();
}
}