Long time no good writing algorithm, so tonight on the realization of the teacher said an algorithm topic: use dynamic programming to solve the digital triangle.
Here is a brief description of the topic:
A number in a digital triangle requires a non-negative integer that is no more than 100. The title rule starts at the top level and selects a path that requires each step along the left slash or right slash, and the sum of the digits on the path is the maximum.
For example, a triangle like the following:
1.7
2.3 8
3.8 1 0
4.2 7 7 4
5.5 5 2 6 5
It has 5 rows of data with a path number and a maximum value of 30.
Note: The triangle of the original topic is equilateral, and we record it as a right triangle in practice. At this point, every step of it is to go down or go along a diagonal line.
Thinking: How to solve such a problem?
Now that the maximum path is required, we calculate and store the number and the starting point of each line in each row. The last line of the path and the information can be compared to achieve.
Reference Code
/************************************************************************* * * > NAME:NUM_TRIANGLE.C * ; Author:liyingxiao (Sweethreart502) * * > mail:liyingxiao502@gmail.com * * > Blog:http://blog.csdn.ne t/u013166575 * * > Created time:2015 year November 19 Thursday 23:32 00 seconds *******************************************************
/#include <stdio.h> #define N 5//processing function int process (int N);
int main (int argc, char * argv[]) {//int n;
int Max;
printf ("Enter the number of lines for the number triangle: \ n");
scanf ("%d", &n);
max = Process (N);
printf ("\ n max Path and for%d.\n", Max);
return 0;
//core processing function int process (int n) {int a[6][6] = {{0}, {0}, {0}, {0}, {0}, {0}};
int I, J;
int T1, T2;
int max = 0;
Initializes the digital triangle printf ("Enter the data information for each row of the digital triangle: \ n");
for (i = 1; I <= n; i++) {printf ("Enter line%d data information: \ n", i); for (j = 1;J <= I;
J + +) {scanf ("%d", &a[i][j]);
The maximum distance of each element of each row to the starting point for (i = 2; I <= n; i++) {for (j = 1; J <= I; j +) {
T1 = A[i][j] + a[i-1][j-1];
T2 = A[i][j] + a[i-1][j];
if (T1 > T2) {a[i][j] = T1;
else {a[i][j] = t2;
}///Compare last row of data information, output maximum for (i = 1; I <= n; i++) {if (A[n][i] > max) {
max = A[n][i];
} return max; }
My code implementation relies on storing the array as a n+1 row n+1 column, with a value of 0 being 0, which is why:
For a globally unified implementation, I start with the second line of the triangle to calculate the maximum data for each of its elements to arrive at the starting point, using the calculation method a[i][j] = max (a[i-1][j-1], a[i-1][j]) + a[i][j].
It is easy to understand if you have an attempt to analyze on draft paper if you don't understand. -.-
0
0 7
0 3 8
0 8 1 0
0 2 7 7 4
0 5 5 2 6 5
The triangle above is my initial array a.