这个便是这道题的详细解答
http://blog.csdn.net/baidu_28312631/article/details/47418773
借鉴一下大神之作
The Triangle
Description 7 3 8 8 1 0 2 7 4 4 4 5 2 6 5 (Figure 1) Input
Your program is to read from standard input. The first line contains one integer N: the number of rows in the triangle. The following N lines describe the data of the triangle. The number of rows in the triangle is > 1 but <= 100. The numbers in the triangle, all integers, are between 0 and 99.
Output
Your program is to write to standard output. The highest sum is written as an integer.
Sample Input 5 7 3 8 8 1 0 2 7 4 4 4 5 2 6 5 Sample Output 30 Source |
[Submit] [Go Back] [Status] [Discuss]
#include<stdio.h>
#include<algorithm>
using namespace std;
int maxsum[101][101]; //记录下每个地方到最底一层的最短路径
int D[101][101];
int n;
int main()
{
int i,j;
scanf("%d",&n);
for(i=1;i<=n;i++)
for(j=1;j<=i;j++)
scanf("%d",&D[i][j]);
for(i=1;i<=n;i++)
maxsum[n][i]=D[n][i];//把最后一行全部记录到maxsum中
for(i=n-1;i>=1;i--)
for(j=1;j<=i;j++)
maxsum[i][j]=max(maxsum[i+1][j],maxsum[i+1][j+1])+D[i][j]; //从最后一行往上,每一行的数都是(下面的数和右下方的数中最大的一个加上本身)
printf("%d\n",maxsum[1][1]); //maxsum正好是第一个数到最后一行的最短路径
}