题目描述
给定一个如下图所示的数字三角形,从顶部出发,在每一结点可以选择移动至其左下方的结点或移动至其右下方的结点,一直走到底层,要求找出一条路径,使路径上的数字的和最大。
样例
5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
输出:30
算法1
include [HTML_REMOVED]
include [HTML_REMOVED]
include [HTML_REMOVED]
using namespace std;
const int N = 510;
int n;
int f[N][N],w[N][N];
int main()
{
cin >> n;
for (int i = 1; i <= n; i )
for (int j = 1; j <= i; j )
cin>>w[i][j];
for(int j=1;j<=n;j++) f[n][j]=w[n][j];
for (int i = n - 1; i; i -- )
for (int j = 1; j <= i; j ++ )
f[i][j] = max(f[i + 1][j]+w[i][j], f[i + 1][j + 1]+w[i][j]);
cout << f[1][1] << endl;
return 0;
}
算法2
include [HTML_REMOVED]
include [HTML_REMOVED]
include [HTML_REMOVED]
using namespace std;
const int N = 510;
int n;
int f[N][N];
int main()
{
cin >> n;
for (int i = 1; i <= n; i )
for (int j = 1; j <= i; j )
cin>>f[i][j];
for (int i = n - 1; i; i – )
for (int j = 1; j <= i; j ++ )
f[i][j] += max(f[i + 1][j], f[i + 1][j + 1]);
cout << f[1][1] << endl;
return 0;
}