Problem 67 : Maximum path sum II
By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.
3
7 4
2 4 6
8 5 9 3
That is, 3 + 7 + 4 + 9 = 23.
Find the maximum total from top to bottom in triangle.txt (right click and ‘Save Link/Target As…’), a 15K text file containing a triangle with one-hundred rows.
NOTE: This is a much more difficult version of Problem 18. It is not possible to try every route to solve this problem, as there are 299 altogether! If you could check one trillion (1012) routes every second it would take over twenty billion years to check them all. There is an efficient algorithm to solve it. ;o)
C++ 代码
#include <iostream>
#include <fstream>
#include <sstream>
#include <cassert>
using namespace std;
class PE0067
{
private:
static const int max_rows = 100;
int triangleMatrix[max_rows+1][max_rows+1];
void readDataFromFile(char filename[]);
int getMaximumTotalFromTopToBottom(int numOfRows);
public:
void run_unit_test();
int findMaximumTotalInFile();
};
void PE0067::run_unit_test()
{
// 3
// 7 4
// 2 4 6
// 8 5 9 3
memset(triangleMatrix, 0, sizeof(triangleMatrix));
int data[10] = {3, 7, 4, 2, 4, 6, 8, 5, 9, 3};
int i = 0;
for (int row=1; row<=4; row++)
{
for (int col=1; col<=row; col++)
{
triangleMatrix[row][col] = data[i++];
}
}
assert(23 == getMaximumTotalFromTopToBottom(4));
}
int PE0067::findMaximumTotalInFile()
{
readDataFromFile("p067_triangle.txt");
return getMaximumTotalFromTopToBottom(max_rows);
}
void PE0067::readDataFromFile(char filename[])
{
ifstream in(filename);
if (!in) return;
int row = 1, col, number;
char szBuf[512];
memset(triangleMatrix, 0, sizeof(triangleMatrix));
while(in.getline(szBuf, 512))
{
col = 1;
string strText = szBuf;
istringstream s(strText);
while (row>=col)
{
s >> number;
triangleMatrix[row][col++] = number;
}
row++;
}
in.close();
}
int PE0067::getMaximumTotalFromTopToBottom(int numOfRows)
{
int maxTotal = 0;
for(int row=1; row<=numOfRows; row++)
{
for(int col=1; col<=row; col++)
{
triangleMatrix[row][col] += \
max(triangleMatrix[row-1][col-1], triangleMatrix[row-1][col]);
maxTotal = max(maxTotal, triangleMatrix[row][col]);
}
}
return maxTotal;
}
int main()
{
PE0067 pe0067;
pe0067.run_unit_test();
cout << "The maximum total from top to bottom is ";
cout << pe0067.findMaximumTotalInFile() << "." << endl;
return 0;
}
Python代码
import numpy as np
def run_unit_test():
"""
3
7 4
2 4 6
8 5 9 3
"""
triangleMatrix = np.zeros((4+1, 4+1))
i, data = 0, [3, 7, 4, 2, 4, 6, 8, 5, 9, 3]
for row in range(1, 5):
for col in range(1, row+1):
triangleMatrix[row][col] = data[i]
i += 1
assert 23 == getMaximumTotalFromTopToBottom(4, triangleMatrix)
def readDataFromFile(filename):
triangleMatrix = np.zeros((100+1, 100+1))
i, data = 0, []
for line in open(filename).readlines():
data += map(int, line.split())
for row in range(1, 101):
for col in range(1, row+1):
triangleMatrix[row][col] = data[i]
i += 1
return triangleMatrix
def findMaximumTotalInFile():
triangleMatrix = readDataFromFile("p067_triangle.txt")
return getMaximumTotalFromTopToBottom(100, triangleMatrix)
def getMaximumTotalFromTopToBottom(numOfRows, triangleMatrix):
maxTotal = 0
for row in range(1, numOfRows+1):
for col in range(1, row+1):
triangleMatrix[row][col] += \
max(triangleMatrix[row-1][col-1], triangleMatrix[row-1][col])
maxTotal = max(maxTotal, triangleMatrix[row][col])
return int(maxTotal)
def main():
run_unit_test()
print("The maximum total from top to bottom is %d." % findMaximumTotalInFile())
if __name__ == '__main__':
main()

本文探讨了ProjectEuler中Problem67的最大路径和问题,这是一个比Problem18更复杂的版本,涉及寻找一个包含一百行三角形数字的最大路径总和。通过分析,我们提供了C++和Python的解决方案,采用动态规划算法高效地解决了这一挑战。
276





