1. 程式人生 > >動態三角形(動態規劃思想入門)

動態三角形(動態規劃思想入門)

star ber name 做到 tar triangle 解決 算法 log

個人心得:動態規劃是一種隸屬於決策學的一個算法思想,他能夠很好的解決多階段決策問題,這種思想對於我們的生活還是科研都是必不可少的,

需要好生體會,學會動態方程的轉移,做到具體問題具體分析。

那這簡單題目來看吧,動態三角形,很明顯從第一個開始就可以看出來第一個等於下面倆個對角線中最大與自己相加,所以可以用遞歸完成,

當然還有種更加巧妙的就是從後面往前面走,你可以很明顯看到從倒數第二行開始他的最大值應該等於下倆個對角線中的最大值加上自己本身。

所以方程可以這麽表示

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 }



動態三角形(動態規劃思想入門)