动态规划--数字三角形
2014-01-27 18:20
253 查看
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
上传者苗栋栋
思路:最优子结构构成当前最优。定义d[i][j]是从(i, j)出发时能得到的最大和,则本题的解为d[0][0]。
若往左走,则最好的情况是a[i][j]与从(i + 1, j)出发后能得到的最大和,向右走类似,这就有了最优子结构,也可以叫做全局最优解包含局部最优解。
首先,最底层也就是第n层每个位置的最大和都是a
[i],因为再向下没有路了,从n - 1层到第一层都是看两种情况:向左走和最大,和向右走和最大,哪个更大,就选哪个跟当前的a[i][j]相加,也就构成了当前状态的最优解。而我们刚刚是逆序看层,从第n层往上走,这也就满足了求d[i][j]时
d[i + 1][j], d[i + 1][j + 1]都已求出。
#include<stdio.h> int max(int a, int b){ return a > b ? a : b; } int main(){ int n, i, j, a[101][101], d[101][101]; scanf("%d", &n); for(i = 0; i < n; i++) for(j = 0; j <= i; j++) scanf("%d", &a[i][j]); for(i = 0; i < n; i++) d[n - 1][i] = a[n - 1][i]; for(i = n - 2; i >= 0; i--){ for(j = 0; j <= i; j++){ d[i][j] = a[i][j] + max(d[i + 1][j], d[i + 1][j + 1]); } } printf("%d\n", d[0][0]); return 0; }
相关文章推荐
- Problem A: 动态规划基础题目之数字三角形
- 七:动态规划-数字三角形
- 动态规划之数字三角形
- 经典动态规划问题--数字三角形 POJ--1163
- YTU OJ 3134: 动态规划基础题目之数字三角形(Java解题)
- 动态规划 问题之数字三角形(正序递推)
- 动态规划____类数字三角形
- YTU.3134: 动态规划基础题目之数字三角形
- 算法 -- 数字三角形之动态规划
- 动态规划入门-数字三角形
- 简单动态规划---动态的数字三角形
- hihocoder#1037 : 数字三角形 经典简单动态规划
- 算法:动态规划-数字三角形的最优解(打印路径)
- 动态规划_数字三角形
- 动态规划--(数字三角形 poj1163)
- 动态规划入门-POJ 1163-The Triangle(数字三角形)
- 动态规划 数字三角形
- 动态规划_数字三角形
- 动态规划--数字三角形问题
- 动态规划--数字三角形