Sums in a Triangle
Let's consider a triangle of numbers in which a number appears in the first line, two numbers appear in the second line, three in the third line, etc. Develop a program which will compute the largest of the sums of numbers that appear on the paths starting from the top towards the base, so that:
- on each path the next number is located on the row below, more precisely either directly below or below and one place to the right;
- The number of rows is strictly positive, but less than 100
- All numbers are positive integers between O and 99.
Input
In the first line integer n - the number of test cases (equal to about 1000). Then n test cases follow. Each test case starts with the number of lines which is followed by their content.
Output
For each test case write the determined value in a separate line.
Example
Input:
2
3
1
2 1
1 2 3
4
1
1 2
4 1 2
2 3 1 1
Output:
5
9
2
3
1
2 1
1 2 3
4
1
1 2
4 1 2
2 3 1 1
Output:
5
9
Solution:
#include<stdlib.h>#include<stdio.h>
inline int input()
{
int a=0;
char c;
c=getchar_unlocked();
while(c<33)
{
c=getchar_unlocked();
}
while(c>=33)
{
a=(a<<3)+(a<<1)+(c-'0');
c=getchar_unlocked();
}
return a;
};
int main()
{
int t,n,max,i,j;
int s[100][100],a[100][100];
t=input();
while(t--)
{
n=input();
a[0][0]=input();
s[0][0]=a[0][0];
max=s[0][0];
for(i=1;i<n;i++)
for(j=0;j<=i;j++)
{
a[i][j]=input();
if(j==0)
s[i][j]=s[i-1][j]+a[i][j];
else if(i==j)
s[i][j]=s[i-1][j-1]+a[i][j];
else
{
if(s[i-1][j]>s[i-1][j-1])
{
s[i][j]=s[i-1][j]+a[i][j];
}
else
{
s[i][j]=s[i-1][j-1]+a[i][j];
}
}
if(max<s[i][j])
max=s[i][j];
}
printf("%d\n",max);
}
return 0;
}
No comments:
Post a Comment