The Triangle
| Time Limit: 1000MS |
|
Memory Limit: 10000K |
| Total Submissions: 43993 |
|
Accepted: 26553 |
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 this calculates the highest sum of numbers passed on a route this starts at the top and ends somewhere on The base. Each of the step can go either diagonally down to the left or diagonally down to the right.
Input
Your program was 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 are > 1 but <= 100. The numbers in the triangle, all integers, is between 0 and 99.
Output
Your program is-to-write to standard output. The highest sum is a written as an integer.
Sample Input
573 88 1 0 2 7 4 44 5 2 6 5
Sample Output
30
The first DP question, water over, commemorate a moment ~
Java AC Code
ImportJava.util.Scanner; Public classMain { Public Static voidMain (string[] args) {Scanner sc=NewScanner (system.in); introws =Sc.nextint (); intInput[][] =New int[Rows + 1] [Rows + 1]; intResult[][] =New int[Rows + 1] [Rows + 1];//The maximum result of each point is in the array for(inti = 1; I <= rows; i++) for(intj = 1; J <= I; J + +) {Input[i][j]=Sc.nextint (); } result[1][1] = input[1][1]; DP (input, result); intMax =Integer.min_value; for(inti = 1; I <= rows; i++) {//find the largest one in the last row, which is the result if(Result[rows][i] >max) Max=Result[rows][i]; } System.out.println (max); } Public Static voiddpint[] Input,int[] [] result) { introws = input.length-1; for(inti = 2; I <= rows; i++) for(intj = 1; J <= I; J + +) { if(j = = 1)//The maximum of the first column of each row and only the maximum of the first column by the previous row and the resultingRESULT[I][J] = Result[i-1][j] +Input[i][j]; Else if(j = = i)//The maximum and maximum of the last column of each row and can only be obtained by the last column on the previous rowRESULT[I][J] = result[i-1][j-1] +Input[i][j]; Else //others can be obtained from the larger one in two directions .RESULT[I][J] = Math.max (Result[i-1][j-1], result[i-1][j]) +Input[i][j]; } }}
POJ 1163 the Triangle (DP)