动态三角形(动态规划思想入门)

个人心得:动态规划是一种隶属于决策学的一个算法思想,他能够很好的解决多阶段决策问题,这种思想对于我们的生活还是科研都是必不可少的,

需要好生体会,学会动态方程的转移,做到具体问题具体分析。

那这简单题目来看吧,动态三角形,很明显从第一个开始就可以看出来第一个等于下面俩个对角线中最大与自己相加,所以可以用递归完成,

当然还有种更加巧妙的就是从后面往前面走,你可以很明显看到从倒数第二行开始他的最大值应该等于下俩个对角线中的最大值加上自己本身。

所以方程可以这么表示                 

DP[i][j]=max(DP[i+1][j],DP[i+1][j+1])+map[i][j];(1=<i<=n-1)这是从后面递推的

             map[i][j] if(i==n)

dp(i,j)=

             max(dp(i+1,j),dp(i+1,j+1))+map[i][j];这是递归方程式

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
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cmath>
 4 #include<cstring>
 5 #include<iomanip>
 6 #include<algorithm>
 7 using namespace std;
 8 int mapa[105][105];
 9 int dp[105][105];
10 int n;
11 int dps(int x,int y){
12     if(dp[x][y]!=-1) return dp[x][y];
13     if(x==n)
14     {
15         dp[x][y]=mapa[x][y];
16         return dp[x][y];
17     }
18     return dp[x][y]=max(dps(x+1,y),dps(x+1,y+1))+mapa[x][y];
19 
20 }
21 int main()
22 {
23     cin>>n;
24     for(int i=1;i<=n;i++)
25         for(int j=1;j<=n;j++)
26             dp[i][j]=-1;
27     for(int i=1;i<=n;i++)
28         for(int j=1;j<=i;j++)
29              cin>>mapa[i][j];
30         cout<<dps(1,1)<<endl;;
31 
32 }

 



posted @ 2017-08-12 11:23  余生漫漫浪  阅读(1780)  评论(0编辑  收藏  举报