Description
晶晶最近迷上了数字迷宫游戏,整天沉浸在一串串看似简单的数字中自得其乐。数字迷宫游戏的魅力体现在变化中隐含着不变的规律,归纳是探究数字迷宫的法宝之一。图10.1-1就是一个由线连接起来的数字小方格组成的数字迷塔。
这个迷塔共n层,它由n×(n+1)/2个小方格组成。每个小方格中都有一个数字,并且连着下一层的两个小方格。现从塔顶走到塔底,每一步只能走到相邻的方格中,则经过方格的数字之和最大值是多少?这个问题晶晶已经琢磨一天了,她感觉异常棘手。你能帮帮她吗?
Input
输入数据共n+1行,第1行是一个整数n(1≤n≤1000),表示数字迷塔的高度,接下来用n行数字表示数字迷塔,其中第i行有i个正整数,且所有的正整数均不大于100。
Output
输出可能得到的最大和。
Sample Input
5
9
12 15
10 6 8
2 18 9 5
19 7 10 4 16
Sample Output
59
HINT
样例说明:9→12→10→18→10
分析:从倒数第二行开始,选择它下边较大的数,加到这一位上,更新数值,最后到第一行第一个,输出a[1][1]即可。
代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <stack>
#include <queue>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
#define M 1010
int a[M][M];
int main()
{
int n;
// freopen("in.txt", "r", stdin);
scanf("%d",&n);
for(int i=1; i<=n; i++)
for(int j=1; j<=i; j++)
scanf("%d", &a[i][j]);
for(int i=n-1; i>=1; i--)
for(int j=1; j<=i; j++)
{
a[i][j] = a[i][j]+ max(a[i+1][j], a[i+1][j+1] );
}
printf("%d\n",a[1][1]);
return 0;
}