Algorithm training Digital Triangle time limit: 1.0s memory Limit: 256.0MB problem description (Figure 3.1-1) shows a digital triangle. Please compile a program to compute a path from top to bottom
diameter, so that the path passes the sum of the largest number.
Each step can be along the left slash down or right slash down;
1< triangle row number ≤100;
The numbers in the triangle are integers 0, 1, ... 99;
.
(Figure 3.1-1) The number of lines of the triangle that is first read in the input format file.
Next, describe the entire triangle output format maximum sum (integer) sample input 5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5 Example output 30
Recursive method: Easy to understand, but easy to timeout
#include <iostream>
#include <cstdlib>
#define ABS (A) (((a) >0)? ( (a):(-(a)))
using namespace std;
int getmax (int * * (&), int, int, int limit);
int main (void)
{
int n; Number of rows
cin >> N;
int **tri;
Tri = new int* [n];
for (int i = 0; i < n; i++)
{
* (tri + i) = new int [i + 1];
}
for (int i = 0; i < n; i++)
{for
(int j = 0; J <= i; j)
Cin >> Tri [i] [j];
}
cout << getmax (tri, 0, 0, N) << Endl;
System ("pause");
return 0;
}
int Getmax (int **&tri, int m, int n, int limit)
{
int sum = tri [m] [n];
int L, R;
if (M < limit-1 && n<limit-1)
{
L = sum + getmax (tri, M + 1, n, limit);
r = sum + getmax (tri, M + 1, n + 1, limit);
}
else
{
L = sum;
r = sum;
}
if (L > R)
{return
l;
}
else if (L < R)
{return
R;
}
}
The second method: short.
#include <iostream>
#include <cstdlib>
using namespace std;
int main (void)
{
int n; Number of rows
cin >> N;
int **tri;
Tri = new int* [n];
for (int i = 0; i < n; i++)
{
* (tri + i) = new int [i + 1];
}
for (int i = 0; i < n; i++)
{for
(int j = 0; J <= i; j)
Cin >> Tri [i] [j];
} for
(int i = n-1 i > 0; i--)
{for
(int j = 0; j<i; j)
{
if (tri [i] [J]>tri [i] [j + 1])
{
tri [i-1] [ J] + = tri [i] [j];
}
else
{
tri [i-1] [j] + = tri [i] [j + 1];
}
}} cout << Tri [0] [0] << Endl;
System ("pause");
return 0;
}