A triangle optimal path problem for dynamic programming practice

Source: Internet
Author: User
Describe

A triangle of positive integer numbers, as shown below:
7
3 8
8 1 0
2 7 4 4
4 5 2) 6 5

There are many different paths from the top of the triangle to the bottom. For each path, add up the number above the path to get one and, and the largest path is called the best path. Your task is to find the sum of the numbers on the best path.
Note: Each step on the path can only go from one number to the next and to the number of its nearest bottom (just below) or to the right (bottom right).
Enter the first behavior triangle height 100>=h>=1, which is also the number of the lowest edge.
Starting with the second line, the number of the corresponding row of each action triangle is separated by a space. The length value of the output best path. Sample input

5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
or
1
8
Sample output

30 or 8 ideas:
For this, the largest and, the top of the number, to choose, the bottom of the two number of the maximum value, and then the overall maximum is equal to the first number of triangular edges plus the number of the largest of the two numbers, and then the second row of the two numbers in the same vein, looking for the third row the largest number. But this looks from top to bottom, obviously not, so from the penultimate line, in turn, a[1][1] is the maximum path and.

#if  1                              
#include <iostream>
using namespace std;
int main ()
{
	int a[105][105],n;
	cin>>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>=1;i--) for
	(int j=1;j<=i;j++)
{
	if (a[i+1][j]>=a[i+1][j+1]) a[i][j]+=a[i+1 ][J];
	else 
	a[i][j]+=a[i+1][j+1];
}
	
	cout<<a[1][1]<<endl;
}

#endif

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.