【发布时间】:2011-01-23 06:19:39
【问题描述】:
嘿,一直在 Project Euler 工作,这个给我带来了一些问题
从下面三角形的顶部开始,移动到下一行的相邻数字,从上到下的最大总数为 23。
3
7 4
2 4 6
8 5 9 3
即 3 + 7 + 4 + 9 = 23。
找出下面三角形从上到下的最大值:
...
注意:由于只有 16384 条路线,因此可以通过尝试每条路线来解决此问题。然而,第 67 题是同样的挑战,包含 100 行的三角形;不能靠蛮力解决,需要巧妙的方法! ;o)
这是我用来解决它的算法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Problem18
{
class Program
{
static void Main(string[] args)
{
string triangle = @"75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23";
string[] rows = triangle.Split('\n');
int currindex = 1;
int total = int.Parse(rows[0]);
Console.WriteLine(rows[0]);
for (int i = 1; i < rows.Length; i++)
{
string[] array1 = rows[i].Split(' ');
if (array1.Length > 1)
{
if (int.Parse(array1[currindex - 1]) > int.Parse(array1[currindex]))
{
Console.WriteLine(array1[currindex - 1]);
total += int.Parse(array1[currindex - 1]);
}
else
{
Console.WriteLine(array1[currindex]);
total += int.Parse(array1[currindex]);
currindex++;
}
}
}
Console.WriteLine("Total: " + total);
Console.ReadKey();
}
}
}
现在每当我运行它时,它都会出现 1064,仅比解决方案少 10 - 1074
我没有发现算法有任何问题,我手工解决了这个问题,还提出了 1064,任何人都知道解决方案是否错误,我将问题解释错误,或者是否只是存在缺陷算法?
【问题讨论】:
-
75+64+82+87+82+75+73+28+83+32+91+78+58+73+93 = 1074
标签: c#