題目描述 Description
如圖所示的數字三角形,從頂部出發,在每一結點可以選擇向左走或得向右走,一直走到底層,要求找出一條路徑,使路徑上的值最大。
輸入描述 Input Description
第一行是數塔層數N(1<=N<=100)。
第二行起,按數塔圖形,有一個或多個的整數,表示該層節點的值,共有N行。
輸出描述 Output Description
輸出最大值。
樣例輸入 Sample Input
5
13
11 8
12 7 26
6 14 15 8
12 7 13 24 11
樣例輸出 Sample Output
86
數據範圍及提示 Data Size & Hint
數字三角形
分類標籤 Tags 點此展開
解題思路:
這道題是一道很經典的題目了,定義狀態爲:dp[i][j]表示,從第i行第j個數字到最後一行的某個數字的權值最大的和。那麼我們最後只需要輸出dp[1][1]就是答案了.
狀態轉移方程爲:dp[i][j] += max( dp[i+1][j+1],dp[i+1][j] );好了, 從第n-1行往上面倒退就好了。
代碼:
# include<cstdio>
# include<iostream>
# include<algorithm>
# include<cstring>
# include<string>
# include<cmath>
# include<queue>
# include<stack>
# include<set>
# include<map>
using namespace std;
# define inf 999999999
# define MAX 123
int a[MAX][MAX];
int main(void)
{
int n;
while ( cin>>n )
{
for ( int i = 1;i <= n;i++ )
{
for ( int j = 1;j <= i;j++ )
{
cin>>a[i][j];
}
}
for ( int i = n-1;i >= 1;i-- )
{
for ( int j = 1;j <= i;j++ )
{
a[i][j] = max(a[i+1][j],a[i+1][j+1])+a[i][j];
}
}
printf("%d\n",a[1][1]);
}
return 0;
}