Algorithm training Digital Triangle time limit: 1.0s memory Limit: 256.0MB problem description (Figure 3.1-1) shows a number triangle. Please compile a program to calculate a route from top to bottom somewhere.
So that the sum of the numbers passed by the path is the largest.
Each step can be left diagonally downward or right slash down;
1< triangle row number ≤100;
The number in the triangle is an integer 0, 1, ... 99;
.
(Figure 3.1-1) The number of rows in the input format file that were first read in the triangle.
Next describes the entire Triangle output format maximum sum (integer) sample input 5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5 sample output 30
Topic Analysis:
The subject relates to an algorithm--the Division and treatment method.
The basic idea of divide and conquer law:
The divide-and- conquer method can be interpreted as a popular interpretation of the decomposition of a territory into pieces of small chunks, and then a piece of land occupied by conquest, broken down can be different political factions or whatever, and then let them alienated each other.
the essence of Divide and conquer law:
Divide the problem into smaller sub-problems;
of these smaller sub-problems;
Merge-The solved sub-problem is merged, and finally the solution of the "mother" problem is obtained.
Place a number triangle in a two-dimensional array. Starting from the penultimate line, line up, each number plus its next row the same column and the next row in the right column
The largest number in the list.
the path is the largest and the first number in the array. Example code:
1 ImportJava.io.BufferedReader;2 Importjava.io.IOException;3 ImportJava.io.InputStreamReader;4 5 Public classMain {6 Private Static intRow//Number of rows7 Private Static int[] arr;8 Public Static voidMain (string[] args)throwsNumberFormatException, IOException {9BufferedReader br =NewBufferedReader (NewInputStreamReader (system.in));Tenrow =Integer.parseint (Br.readline ()); Onearr =New int[Row][row]; A - for(inti = 0; i < row; i++){ -string[] str = Br.readline (). Split (""); the for(intj = 0; J <= I; J + +){ -ARR[I][J] =Integer.parseint (Str[j]); - } - } + - intMaxsum =maxsum (Row,arr); + A System.out.println (maxsum); at } - /** - * Maximum and - * @paramRow number of rows - * @paramarr Array - * @returnthe path of the maximum and in */ - Private Static intMaxsum (intRowint[] arr) { to for(inti = row-2; I >= 0; i--){ + for(intj = 0; J <= I; J + +){ -ARR[I][J] + = Maxnum (arr[i+1][j), arr[i+1][j+1]); the } * } $ returnArr[0][0];Panax Notoginseng } - the /** + * Find the maximum number of two A * @parama the * @paramb + * @returnMaximum number - */ $ Private Static intMaxnum (intAintb) { $ returnA>b?a:b; - } -}
Blue Bridge Cup algorithm training ALGO-124 digital triangles