ACM---The Triangle-1163

Description
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
(Figure 1)

Figure 1 shows a number triangle. Write a program that calculates the highest sum of numbers passed on a route that starts at the top and ends somewhere on the base. Each step can go either diagonally down to the left or diagonally down to the right.
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
思路:
要得到整条路径走完后的最大值,可以变相的看把最大值加到第一行的数,得到第一行的最大值,需要把第一行和第二行的某个最大值相加,而得到第二行的某个数的最大值,又需要把第二行的数据与第三行的最大值相加,层层递推吧。

程序代码如下

#include<stdio.h>
#include<math.h>

//最大值计算,算是一个递推的问题,从结果开始推,一直推到最底层
int max(int a,int b)
{
    if (a> b) {
        return a;
    } else {
        return b;
    }
}

int main() {

    int n,i,j,m,k;
    int resultArr[100][100];
    int result = 0;

    scanf("%d\n",&n);
    for(i=0; i<n; i++) 
    {
        for(j = 0; j <= i; j ++)
        {
            int in;
            scanf("%d",&in);
            resultArr[i][j] = in;
        }
    }

    for(m=n-2;m>=0;m--)
    {
       for(k = 0;k <= m;k ++)
       {
           resultArr[m][k]+=max(resultArr[m+1][k],resultArr[m+1][k+1]);
       }
    }

    printf("%d\n",resultArr[0][0]);

    return 0;
}
//PS:终于遇到一个喜欢的题目。。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,891评论 0 23
  • 同样的距离 同样的时间 不一样的心情 来的时候满心欢喜与期待 走的时候满脸的悲伤与无奈 一天的的千里颠簸,半生的心...
    苦行僧与树阅读 143评论 0 0
  • 我们走着,走着,就散了…… 我看不见你了…… 你也看不见...
    西门吹雪一一匠心做灯人阅读 287评论 0 0
  • 议题:感情(刚失恋,觉得自己为什么不能谈一段正常的恋爱)首先明确了一下什么是正常的恋爱,自己的恋爱怎么就不正常了?...
    塔罗师cat阅读 255评论 0 0
  • 特别顽劣的猴崽子: 崽儿啊!阔别这么多年还是习惯称呼你叫崽子,崽儿啊!师傅已经收到了您的来信,特别开心您还想着为...
    大大师阅读 234评论 0 0