A number triangle is shown. Please make a program to calculate a path from the top to the bottom, so that the total number of the path is the largest.
Each step can go down along the left diagonal or the right diagonal
1 < number of triangle lines < 25
Numbers in triangles are integers < 1000;
Enter the first line N, which means there are N lines after N lines, which means the path weight of each path of the triangle
The answer with the largest sum of numbers passed by the output path
sample input
5 7 3 8 8 1 0 2 7 4 4 4 5 2 6 5
sample output
30
Question link: Path weight of JSK-243 triangle
Problem Description: (omitted)
Problem analysis:
This is a dynamic programming problem. There are two solutions.
Method 1:
No extra arrays, top down.
Method 2:
Use extra arrays, calculated from the bottom up. You need to pay attention to the array size! One more row and one more column to ensure reliability.
Procedure description: (omitted)
Reference link: HDU2084 data tower [DP]
Title: the calculation speed of dynamic programming algorithm is often fast.
The C language program of AC is as follows:
/* JSK-243 Path weight of triangle */ #include <stdio.h> #include <string.h> #define MAX(a, b) (((a) > (b)) ? (a) : (b)) #define N 25 int a[N + 1][N + 1], dp[N + 1][N + 1]; int main() { int n; while(scanf("%d", &n) != EOF) { for(int i=0; i<n; i++) for(int j=0; j<=i; j++) scanf("%d", &a[i][j]); memset(dp, 0, sizeof(dp)); for(int i=n-1; i>=0; i--) for(int j=0; j<=i; j++) dp[i][j] = MAX(dp[i+1][j],dp[i+1][j+1]) + a[i][j]; printf("%d\n", dp[0][0]); } return 0; }
The C language program of AC is as follows:
/* JSK-243 Path weight of triangle */ #include <stdio.h> #include <string.h> #define MAX(a, b) (((a) > (b)) ? (a) : (b)) #define N 25 int a[N][N]; int solve(int n) { for(int i=1; i<n; i++) for(int j=0; j<=i; j++) if(j == 0) a[i][j] += a[i-1][j]; else a[i][j] = MAX(a[i][j] + a[i-1][j-1], a[i][j] + a[i-1][j]); int ans = 0; for(int i=n-1, j=0; j<n; j++) if(a[i][j] > ans) ans = a[i][j]; return ans; } int main() { int n; while(scanf("%d", &n) != EOF) { memset(a, 0, sizeof(a)); for(int i=0; i<n; i++) for(int j=0; j<=i; j++) scanf("%d", &a[i][j]); int ans = solve(n); printf("%d\n", ans); } return 0; }