[3-4] digital Triangles

'Description of the problem:
Given a number of n-row numbers triangle as shown below. Try to design an algorithm to calculate from the triangle
path is top to bottom, so that the digital sum of the maximum path passes.
. 7
. 3. 8
. 8. 1 0
2. 7. 4. 4
. 4. 5. 6 2. 5
'programming tasks:
for a given digital triangle formed by the n-th row of numbers, the number of the elapsed programming paths from top to bottom of the triangle of
the word and a maximum value .
'Input Data:
provided by the input data file input.txt. The first line is the digital triangle file number of rows n, 1 £ n £ 100. Continued
to row n is the number of row numbers of each triangle. All numbers between 0..99.
'Output Results:
At the end of run, outputs the calculation result to the file output.txt. The number of rows in the first file is to calculate
a maximum value out.
Sample output file sample input file
input.txt output.txt
. 5
. 7
. 3. 8
. 8. 1 0
2. 7. 4. 4
. 4. 5. 6. 5 2
30

【answer】


/
Set f [i] [j] denotes the (1,1) come (i, j) of the maximum value
f [i] [j] = max (f [i-1] [j], f [i- . 1] [-J. 1]) + A [I] [J];
/

[Code]

#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

const int N = 100;

int f[N + 10][N + 10];
int n, a[N + 10][N + 10];

int main() {
    //freopen("C://Users//Administrator//Desktop//测试数据//ch3//prog34//test//tri6.in","r",stdin);
    cin >> n;
    for (int i = 1;i <= n;i++)
        for (int j = 1; j <= i; j++) {
            cin >> a[i][j];
        }
    f[1][1] = a[1][1];
    for (int i = 2; i <= n; i++) {
        for (int j = 1; j <= i; j++) {
            f[i][j] = max(f[i - 1][j], f[i - 1][j - 1]) + a[i][j];
        }
    }
    int ans = f[n][1];
    for (int i = 1; i <= n; i++) {
        ans = max(ans, f[n][i]); 
    }
    cout << ans << endl;
    return 0;
}

Guess you like

Origin www.cnblogs.com/AWCXV/p/11665414.html