1004 .The Triangle

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. 
 

 

碎碎念:这道题最开始的时候想的过于复杂,思路逻辑都不好,在自己思考以及别人提示的情况下花了一两个小时把它编程实现。

这次是第二次看这道题,思路很直观,很直接。算法很大程度成应该都是在模拟人的思维思路。所以很简单考虑一下自己对于这道题会怎么算就好了。

 

思路:思路很直接,从第一层算到最后一层,再比较最后一层,得出最大的结果。

如第一层加到第二层上,第二层从 3  8,变为10 15,第二层从8 1 0,变为18  16  15(对于第三层原本的1,应在比较后加第二层的较大一个),第四层为20 25 20 19,第五层为 24 30 27 26 24。 再比较最后一行得出结果为30。

 

代码如下:

#include<stdio.h>
#include<iostream>
int main()
{
    int n;
    while(scanf("%d",&n)!=EOF)
    {
        ///声明数组
        int **p=NULL;
        p=new int*[n];
        for(int i=0;i<n;i++)
        {
           p[i]=new int [i+1];
        }
        ///输入数组
        for(int i=0;i<n;i++)///每一行
        {
            for(int j=0;j<=i;j++)///每一列
            {
                scanf("%d",&p[i][j]);
            }
        }

        //判断数组
        for(int i=1;i<n;i++)///每一行
        {
            for(int j=0;j<=i;j++)///每一列
            {
                if (j == 0)
					p[i][j] += p[i - 1][0];
				else if (j == i)
					p[i][j] +=p[i - 1][j - 1];
				else
				{
					if (p[i - 1][j - 1] >= p[i - 1][j])
						p[i][j] +=p[i - 1][j - 1];
					else
						p[i][j] += p[i - 1][j];
                }
             }
          }
        //找出最后一行的最大值
        int max = p[n-1][0];
			for (int j = 1; j<n; j++)
			{
				if (max<p[n-1][j])
					max = p[n-1][j];
			}
        printf("%d\n", max);
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章