首页 > Linux操作系统 > Linux操作系统 > 我写的找重复数和过桥问题.
static void Main(string[] args)
{
//定义数组
int[] list = new int[1001];
Random random = new Random();
for (int i = 1; i < 1001; i++)
{
list[i - 1] = i;
}
list[1000] = random.Next(1, 1000);
Console.WriteLine(add(1, list) - (1 + 1000) * 500);
Console.Read();
}
//递归算法
public static int add(int i,int[] list)
{
if (i < list.Length)
{
return list[i - 1] + add(++i, list);
}
else
return list[i - 1];
}
class Program
{
static void Main(string[] args)
{
List<Woman> w = new List<Woman>();
w.Add(new Woman { Min = 1, Where = 0, WID = 1 });
w.Add(new Woman { Min = 2, Where = 0, WID = 2 });
w.Add(new Woman { Min = 5, Where = 0, WID = 3 });
w.Add(new Woman { Min = 10, Where = 0, WID = 4 });
w.Add(new Woman { Min = 15, Where = 0, WID = 5 });
w.Add(new Woman { Min = 5, Where = 0, WID = 6 });
WomenGapBridge womenGapBridge =
new WomenGapBridge(w);
womenGapBridge.GapBridge();
Console.ReadLine();
}
}
class Woman {
public int WID { set; get; }
public int Min { set; get; }
public byte Where { set; get; }
}
class WomenGapBridge {
private int num = 0;
private int gonum = 1;
private int UseTime = 0;
List<Woman> Women;
public WomenGapBridge(List<Woman> w)
{
this.Women = w;
num = w.Count;
foreach (var n in w)
{
Console.WriteLine(string.Format("No.{0},过桥需要{1}分钟", n.WID, n.Min));
}
}
public void GapBridge()
{
while(Women.Exists(s=>s.Where==0))
{
Go();
}
Console.WriteLine(string.Format("总用时{0}分", UseTime));
}
public void Go()
{
IEnumerable<Woman> n1;

if (gonum % 2 == 0)
{
n1 = (from s in Women
where s.Where == 0
orderby s.Min descending
select s).Take(2);
}
else
{
n1 = (from s in Women
where s.Where == 0
orderby s.Min ascending
select s).Take(2);
}
int maxTime = 0;
foreach (var n in n1)
{
if (n.Min > maxTime)
maxTime = n.Min;
Console.WriteLine(string.Format("No.{0} 过河", n.WID));
n.Where = 1;
}
Console.WriteLine(string.Format("用时:{0}分",maxTime));
UseTime += maxTime;
gonum++;
if (gonum < (num))
{
Back();
}
}
public void Back()
{
var back = (from s in Women
where s.Where == 1
orderby s.Min ascending
select s).Take(1).First<Woman>();
back.Where = 0;
UseTime += back.Min;
Console.WriteLine(string.Format("No.{0} 回去", back.WID));
Console.WriteLine(string.Format("用时:{0}分", back.Min));
}
}来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/12639172/viewspace-609971/ ,如需转载,请注明出处,否则将追究法律责任。