数字三角形
2016-04-04 10:11
281 查看
The Triangle
时间限制:1000 ms | 内存限制:65535 KB难度:4
描述
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 [1]; for(j=2;j<=n;j++) { if(a [j]>max) max=a [j]; } printf("%d",max); return 0; } </span>
方法二思想:
从下往上走——定义一个二维数组a[n+1][n+1],给最后一行初始化为数字三角形的最后一层,然后从底部往上顶走,直到走到顶部剩一个元素则为最大值。[b]对数组元素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],[b]a[i+1][j+1] [/b] )+a[i][j].[/b]
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; }
相关文章推荐
- 算法习题16:输入一颗二元树,从上往下按层打印树的每个结点,同一层中按照从左往右的顺序打印
- 程序员面试题精选100题(12)-从上往下遍历二元树[数据结构]
- 2013 锦标赛
- C++第2次实验作业
- Adobe Photoshop CC 打开时报错~配置错误:请卸载并重新安装该产品
- javascript事件委托的用法及其好处简析
- vim简单操作指令
- Angels Fall First --Nightwish 翻译
- B0M
- 快速幂(转)
- Java WebService 简单实例
- 基于zookeeper实现配置集中管理【转】
- Tomcat数据库连接池配置
- 将字符串转换成对应的整数(简单版,后续会出复杂版的)
- 简单的NFA转DFA的代码实现
- linux系统中内存爆满之后会如何?
- linux系统中内存爆满之后会如何?
- linux系统中内存爆满之后会如何?
- Android课程---Android ImageView的scaleType属性与adjustViewBounds属性(转)
- DOM