The third chapter of the report Hands algorithm digital triangle

1. Practice topic

7-1 Digital triangle (30)
 

Given a digital triangle formed by the n-th row numbers as shown in FIG. Try to design an algorithm to calculate a path from top to bottom of the triangle (each step downward along the left diagonal down or right diagonal), so that the digital sum of the maximum path passes.

QQ screenshot 20170929023616.jpg

Input formats:

Row n + 1 is input:

Line 1 is the number of rows triangular n, 1 <= n <= 100.

The next row n is the number of triangles in each row numbers. All numbers between 0..99.

Output formats:

The maximum value of the output path.

Sample input:

Here we are given a set of inputs. E.g:

5 
7 
3 8 
8 1 0 
2 7 4 4
4 5 2 6 5 

Sample output:

Given here corresponding output. E.g:

30

2.问题描述
  思路:从数字三角的的倒数第二行(n-1)【2,7,4,4】行开始往上,取(n-1)行的下一行,即第n行【4,5,2,6,5】,将(n-1)行的第一个元素2与它的下一行第一个元素4以及下一行的第二个元素5分别相加取最大值,即max(2+4,2+5),将max存入n-1行的第一个元素,依次循环得到从n行到n-1行的值存在n-1行。n-行继续向上,最后顶端的数字即最长路径数。
3.算法描述
-----------------------------------------------------------------------------------------------------------------------------------
#include<iostream>
using namespace std;
int res [1005] [1005];
int a[1005][1005];
int main ()
{
    int n,maxn=0;
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=i;j++)
        {
             cin >> a[i][j];
        }
    }
    for(int i=n-1;i>0;i--)
    {
        for(int j=1;j<=i;j++)
        {
            a[i][j]+=max(a[i+1][j],a[i+1][j+1]);
        }
    }
    cout << a[1][1] << endl;
    return 0;
}
----------------------------------------------------------------------------------------------------------------------------------------------------------------------
3. The time complexity of the algorithm and spatial analysis
The time complexity is O (n2), has two floors for circulation at the time of dynamic programming, and only one statement. Space complexity is O (n2), creates a two-dimensional array, each row of each column are n, it is O (n2).
4. experiences (The practice of harvesting and doubts summarize)
A triangular numbers beginning no idea, until suddenly have ideas. For each question should carefully think about it, do not rush to knock code.

Guess you like

Origin www.cnblogs.com/lycsuper/p/11703468.html