Digital triangle Problems
Memory limit: 65536kb time limit: 300 ms
Accept: 62 submit: 146
Description
Shows a digital triangle composed of N numbers. Design an algorithm to calculate a path from the top of the triangle to the bottom, so that the total number passing through the path is the largest.
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
For a given number triangle composed of N rows of numbers, calculate the maximum value of the number and the path from the top to bottom of the triangle.
Input
The first line of the input is the number of N, 1 <= n <= 600. The next n rows are numbers in each row of a digital triangle. All numbers are in the range of 0 .. 99.
Output
Output: the maximum value.
Sample Input
5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
Sample output
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<stdlib.h>
using
namespace
std ;
int
Data[605][605];
int
M[605][605];
int
main()
{
int
T = 0 ;
scanf
(
"%d"
,&T) ;
int
k = 1 ;
int
i = 1 ;
int
j = 1 ;
memset
(M,0,
sizeof
(M));
while
(k<=T)
{
for
(j=1;j<=k;j++)
{
scanf
(
"%d"
,&Data[k][j]);
//cout<<"\nData: i: "<<k<<" J:"<<j <<" "<<Data[k][j]<<" ";
}
k++;
}
for
( i =T ; i >=1 ; i -- )
for
(j =1 ; j <= i ; j++ )
{
if
( i ==T )
{
M[i][j] = Data[i][j];
}
else
{
int
a = M[i+1][j] +Data[i][j];
int
b = M[i+1][j+1] +Data[i][j];
a>b ? M[i][j] = a : M[i][j] = b ;
}
// cout<<"\nM: i: "<<i<<" J:"<<j <<" "<<M[i][j]<<" ";
}
cout<<M[1][1]<<endl;
return
0 ;
}