1. 程式人生 > 實用技巧 >1730數字三角形問題(DP)

1730數字三角形問題(DP)

Description

給定一個由n行數字組成的數字三角形如下圖所示。試設計一個演算法,計算出從三角形的頂至底的一條路徑,使該路徑經過的數字總和最大。

對於給定的由n行數字組成的數字三角形,計算從三角形的頂至底的路徑經過的數字和的最大值。

Input

輸入資料的第1行是數字三角形的行數n,1≤n≤100。接下來n行是數字三角形各行中的數字。所有數字在0..99之間。

Output

輸出資料只有一個整數,表示計算出的最大值。

Sample

Input

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

Output

30

Hint

 1 #include <iostream>
 2
#include <stdio.h> 3 #include <string> 4 #include <string.h> 5 #include <algorithm> 6 #include <math.h> 7 #include <map> 8 #include <vector> 9 10 #define inf 0x3f3f3f3f 11 12 using namespace std; 13 14 int main() 15 { 16 int n, i, j; 17 int a[105
][105], dp[105][105]; 18 cin >> n; 19 for(i=0;i<n;i++) 20 { 21 for(j=0;j<=i;j++) 22 { 23 cin >> a[i][j]; 24 } 25 } 26 for(i=0;i<n;i++) 27 { 28 dp[n-1][i] = a[n-1][i]; 29 } 30 for(i=n-2;i>=0;i--) 31 { 32 for
(j=0;j<=i;j++) 33 { 34 dp[i][j] = a[i][j] + max(dp[i+1][j], dp[i+1][j+1]); 35 } 36 } 37 cout << dp[0][0] << endl; 38 return 0; 39 }