给定一个由 n行数字组成的数字三角形如下图所示。试设计一个算法,计算出从三角形 的顶至底的一条路径(每一步可沿左斜线向下或右斜线向下),使该路径经过的数字总和最大。
输入格式:
输入有n+1行:
第 1 行是数字三角形的行数 n,1<=n<=100。
接下来 n行是数字三角形各行中的数字。所有数字在0..99 之间。
输出格式:
输出最大路径的值。
输入样例:
在这里给出一组输入。例如:
5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
输出样例:
在这里给出相应的输出。例如:
30
解答:
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <string>
#include <math.h>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <list>
#include <sstream>
const int INF=0x3f3f3f3f;
typedef long long LL;
const int mod=1e9+7;
using namespace std;
#define ARR_SIZE 10001
int max(int a, int b);
int maxNumb(int n);
int a[ARR_SIZE][ARR_SIZE];
int main()
{
int n;
int i = 0, j = 0;
scanf("%d",&n);
for(i = 0; i<n; i++)
{
for(j = 0; j<=i; j++)
{
scanf("%d",&a[i][j]);
}
}
printf("%d",maxNumb(n));
return 0;
}
int max(int a, int b)
{
return (a>b ? a : b);
}
int maxNumb(int n)
{
int i = 0, j = 0;
int x = 0, y = 0;
for(i = (n-2); i>=0; i--)
{
for(j = 0; j<=i; j++)
{
x = a[i+1][j];
y = a[i+1][j+1];
a[i][j] += max(x, y);
}
}
return a[0][0];
}