The Triangle
-
描述
-
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
(Figure 1)
Figure 1 shows a number triangle. Write a program that calculates the highest sum of numbers passed on a route that starts at the top and ends somewhere on the base. Each step can go either diagonally down to the left or diagonally down to the right.-
输入
- Your program is to read from standard input. The first line contains one integer N: the number of rows in the triangle. The following N lines describe the data of the triangle. The number of rows in the triangle is > 1 but <= 100. The numbers in the triangle, all integers, are between 0 and 99. 输出
- Your program is to write to standard output. The highest sum is written as an integer. 样例输入
-
5 7 3 8 8 1 0 2 7 4 4 4 5 2 6 5
样例输出:
30
题目大意:
给出一个数n,表示这个数字三角形有n层,每层的数字个数逐层递增。从第一行的数开始,每次可以往右下或左下走一格,直到走到最后一行,把沿途经过的数都加起来,如何走使得这个数最大?
思想:
方法一思想:从上往下走——将数字三角形存储在二维数组里,对每一个数组元素a[i][j]它要不加上正上方元素a[i-1][j],要不加上左上方元素a[i-1][j-1] 。即a[i][j]=Max(a[i-1][j],a[i-1][j-1] )+a[i][j].
代码如下:
<span style="font-size:18px;">#include <stdio.h> int main(void) { int a[101][101]={0}; int n; int i,j,max; scanf("%d",&n); for(i=1;i<=n;i++) { for(j=1;j<=i;j++) scanf("%d",&a[i][j]); } for(i=1;i<=n;i++) { for(j=1;j<=i;j++) { if(a[i-1][j]>=a[i-1][j-1]) a[i][j]+=a[i-1][j]; else a[i][j]+=a[i-1][j-1]; } } i=n; max=a[n][1]; for(j=2;j<=n;j++) { if(a[n][j]>max) max=a[n][j]; } printf("%d",max); return 0; } </span>
方法二思想:
从下往上走——定义一个二维数组a[n+1][n+1],给最后一行初始化为数字三角形的最后一层,然后从底部往上顶走,直到走到顶部剩一个元素则为最大值。对数组元素a[i][j](i从n-1开始,i--到1.j从1开始,j++到n)它要不加上正下方元素a[i+1][j],要不加上右下方元素a[i+1][j+1] 。即a[i][j]=Max(a[i+1][j],a[i+1][j+1] )+a[i][j].
0 0 0 0 0 0 0 30
0 23 21
0 20 13 10
0 7 12 10 10 0 4 5 2 6 5 代码如下:
#include <stdio.h> int main(void) { int a[101][101]={0}; int b[101][101]={0}; int n; int i,j,max; scanf("%d",&n); for(i=1;i<=n;i++) { for(j=1;j<=i;j++) scanf("%d",&a[i][j]); } //初始化 i=n; for(j=1;j<=n;j++) b[i][j]=a[i][j]; //dp for(i=n-1;i>=1;i--) { for(j=1;j<=n;j++) { if(a[i+1][j]>=a[i+1][j+1]) a[i][j]+=a[i+1][j]; else a[i][j]+=a[i+1][j+1]; } } printf("%d",a[1][1]); return 0; }