Chapter III apply on board

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

问题描述:
从三角形 的顶至底的一条路径(每一步可沿左斜线向下或右斜线向下),使该路径经过的数字总和最大。

算法描述:
声明另一个与输入同样大小的数组,(最后一行可以不用考虑填写,)而其余空从下往上,从左往右开始,从输入数组同样位置的下一行的同一列和下一列数字中选择最大的数字,加上数组原位置上的数,填写如新数组中,填写一个新的表格。逐次往上加,第一行第一列的数即为所要的最大值。

代码:
#include <iostream>
using namespace std;
int d[101][101],w[101][101],n;

void findMax(){
    for(int s=1; s<=n; s++)
        d[n][s]=w[n][s];
    for(int i=n-1; i>=1; i--){
       for(int j=1; j<=i; j++){
              if(d[i+1][j]>=d[i+1][j+1])
                  d[i][j]=w[i][j]+d[i+1][j];
              else
                  d[i][j]=w[i][j]+d[i+1][j+1];
          }
    }
}

int main () {
    cin>>n;
    for(int i=1; i<=n; i++){
        for(int j=1; j<=i; j++){
            cin>>w[i][j];
        }
    }
    findMax();
    cout<<d[1][1];
 
 
Experiences: filling with ideas to solve problems, find ideas compared to the first recursive simple and clear a lot of our team here at this problem and some do not lead us to clarify ideas codes have been questions we can not run properly. Careful analysis analyzes the problems behind their own code only to find there is little cause to fail problem solving using the equation in the initial filling.

Guess you like

Origin www.cnblogs.com/redish/p/11723817.html