动态规划DP(以 POJ 1163 The Triangle为例)

The Triangle

Time Limit: 1000MS   Memory Limit: 10000K
Total Submissions: 57114   Accepted: 34303

Description

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. 

Input

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.

Output

Your program is to write to standard output. The highest sum is written as an integer.

Sample Input

5
7
3 8
8 1 0 
2 7 4 4
4 5 2 6 5

Sample Output

30

Source

IOI 1994

动态规划(DP):

1.将原问题分解为若干子问题

2.确定状态           3.状态转换

4.确定动态转移方程

就是对这道题目来说,如果采用正常的递归思路的话,时间复杂度会是2^n,显然会超时,而且会出现重复计算。

怎么办呢,我们就从最后一行开始,向上搜索,每算出一个maxSum[i[j]]就储存起来,下一次计算的时候直接进行调用,这就是记忆性的递归型动规程序。

还能继续优化:将递归优化成递推,这个时候就改由从最后一行开始往上找上面一行符合要求的数累次相加,加到最后就是最终求的最大值。

还有一种方法是从上往下进行计算,这里还没有进行尝试。

然后呢,可以再进行空间优化也就是把maxSum数组变成一维数组,只需要存储一行的MaxSum数组,逐级更新就可以了。

注:部分内容参考PKU郭炜老师的Acm课件 

猜你喜欢

转载自blog.csdn.net/qq_37618760/article/details/81565184