数字三角形问题
Time Limit: 1000 ms Memory Limit: 65536 KiB
Submit Statistic
Problem 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
Sample Output
30
Hint
Source
采用自底向顶的方法,单独设置一个数组maxx用来存放每一步的最大值,逐步往上
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
int a[110][110];
int maxx[110][110];
memset(maxx,-1,sizeof(maxx));
int n;
cin>>n;
int i,j;
for(i = 1; i <= n; i++)
for(j = 1; j <= i; j++)
cin>>a[i][j];
for(j = 1; j <= n; j++)
{
maxx[n][j] = a[n][j];
}
for(i = n-1; i >= 1; i--)
{
for(j = 1; j <= i; j++)
{
if(maxx[i+1][j] > maxx[i+1][j+1])
maxx[i][j] = a[i][j] + maxx[i+1][j];
else
maxx[i][j] = a[i][j] + maxx[i+1][j+1];
}
}
cout<<maxx[1][1]<<endl;
return 0;
}