1163 The Triangle (Note: Dynamic Planning questions)

Source: Internet
Author: User

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

573 88 1 02 7 4 44 5 2 6 5

Sample Output

30

Code
# Include <iostream>
Using namespace std;
# Define N 101
Int route [N] [N] = {0 };
Int data [N] [N] = {0 };
Int sum (int, int, int );
Int main ()
{
Int I, j, n;

Cin> n;
For (I = 1; I <n + 1; I ++)
For (j = 1; j <= I; j ++)
{Cin> data [I] [j]; route [I] [j] =-1 ;}

Cout <sum (1, 1, n); cin> n;
Return 0;

}

Int sum (int I, int j, int n)
{
If (I = n)
Return data [I] [j];
If (route [I + 1] [j] =-1)
Route [I + 1] [j] = sum (I + 1, j, n );
If (route [I + 1] [j + 1] =-1)
Route [I + 1] [j + 1] = sum (I + 1, j + 1, n );
If (route [I + 1] [j] <route [I + 1] [j + 1])
Return route [I + 1] [j + 1] + data [I] [j];
Else
Return route [I + 1] [j] + data [I] [j];

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.